0
def main() :
    a = Shape()
    b = Shape("red")
    print(a,b)
    c = Circle("blue",False,10)
    print(c)
    print(c.area())

class Shape:
    def __init__(self, color="yellow", filled=True):
        self.__color = color
        self.__filled = filled

    def __str__(self):
        return f'({self.__color},{self.__filled})'

class Circle(Shape):
    def __init__(self, color="yellow", filled=True, radius=0):
        super().__init__(color="yellow", filled=True)
        self.__radius = radius
        self.__color = color
        self.__filled = filled

    def area(self):
        fullArea = 3.14*((self.__radius)**2)
        return fullArea

    def __str__(self):
        return f'({self.__color},{self.__filled})'+f'(radius = {self.__radius})'


main()

I want to get the answer like this:

(yellow,True) (red,True)
(blue,False)(radius = 10)
314.0

and yes I got it but I want to get the answer even if I remove these two sentences because it was inherited:

self.__color = color
self.__filled = filled

When I try to remove that two sentences, this is what I got:

'Circle' object has no attribute '_Circle__color'

Why this happened and what should I fix for proper inheritance?

dkaelfkae
  • 13
  • 3
  • If you don't want that, don't start your attribute name with `__`. The double underscore means "this is private to the declaring class, so mangle the attribute name to prevent it being used outside the class". – khelwood May 22 '21 at 14:28
  • Don't use `__` names (subject to [name mangling](https://docs.python.org/3.3/tutorial/classes.html#private-variables)) unless you have a good reason. That said, you should also read https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ for advice on using `super` correctly. – chepner May 22 '21 at 14:29
  • double underscore is for creating private variables so that u can access only within a class that's why its showing error, to fix this use single underscore variable which is a protected member – Nanthakumar J J May 22 '21 at 14:32

0 Answers0