0

I'm having some trouble when inheriting Shape class which has private instance variables (color, filled).

the given code is:

class Shape:
    def __init__(self, color = "y", filled = True):
        self.__color = color
        self.__filled = filled
    
    def __str__(self):
        return f'({self.__color},{self.__filled})'

class Circle(Shape):
    def __init__(self, color, filled, radius):
        super().__init__(color, filled)
        self.__radius = radius
    
    def __str__(self):
        return f"({self.__color},{self.__filled})(radius = {self.__radius})"


print(Circle("b",True,5))

and the result is:

return f"({self.__color},{self.__filled})(radius = {self.__radius})"

AttributeError: 'Circle' object has no attribute '_Circle__color'

I checked the variables of the Circle instance by using https://pythontutor.com and the visualizer shows like this : python tutor visualizer

So Circle instance has 3 attributes- _Circle__radius, _Shape__color, and _Shape__filled.

When I removed all the underscores to change private variables into public, the visualizer shows that the Circle instance has attributes of color, filled, and radius. (python tutor visualizer)

I think the constructor of the superclass makes the difference when initializing private variables, but there was no explanation of how exactly does it work.

What is the difference and why does it work like that? and, is there any way to solve the problem while keeping variables private?

milk_beat
  • 5
  • 1
  • 1
    There is no such thing as a private variable in Python, use a single underscore to indicate that an attribute is "private". Attributes beginning with two underscores have their name "mangled" to `___` but this is generally just to prevent inheritors from affecting functionality in the superclass – Iain Shelvington May 29 '22 at 08:59

0 Answers0