Python 继承似乎没有得到正确的实现,但是don';我不知道为什么
我想得到这样的答案:Python 继承似乎没有得到正确的实现,但是don';我不知道为什么,python,Python,我想得到这样的答案: 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
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()
是的,我知道了,但我想得到答案,即使我删除了这两句话,因为它是遗传的:
(yellow,True) (red,True)
(blue,False)(radius = 10)
314.0
当我试图删除这两句话时,我得到的是:
self.__color = color
self.__filled = filled
为什么会发生这种情况?我应该为正确的继承修复什么?如果您不想这样做,请不要以
\uuu
开头属性名。双下划线表示“这是声明类的专用名称,因此请损坏属性名称以防止其在类之外使用”。除非有充分的理由,否则不要使用\uuu
名称(取决于)。也就是说,您还应该阅读有关正确使用super
的建议。双下划线用于创建私有变量,以便您只能在类内访问,这就是显示错误的原因,要修复此问题,请使用单下划线变量,它是受保护的成员
'Circle' object has no attribute '_Circle__color'