使用多重继承时引用基类属性

时间:2016-08-18 14:55:52

标签: python attributes multiple-inheritance

class Shape:
 def __init__(self,center,name):
    self.__name = name
    self.center = center

 def getName(self):
    return self.__name

 def __add__(self,otherShape):
    return Shape(name = self.__name, center = self.center + otherShape.center)


class Size:
 def __init__(self,surface,magnitude):
    self.surface = surface
    self.magnitude = magnitude

 def __eq__(self, otherSize):
    try:
        a = self.magnitude == otherSize.magnitude and self.surface == otherSize.surface
    except:
        print('Wrong type of atributes')
    return a 

class Dreieck(Size,Shape):
 def __init__(self,center,name,surface,magnitude,a,b,c):
    Shape.__init__(self,center,name)
    Size.__init__(self,surface,magnitude)
    Dreieck.a = a
    Dreieck.b = b
    Dreieck.c = c
 def pitagoras(self):
    if self.a+self.b==self.c and self.a**2 + self.b**2 == self.c**2:
        return True
    else:
        return False

 def __add__(self,otherDreieck):
    return Dreieck(self.center, self.__name, self.surface, self.magnitude,self.a+otherDreieck.a, self.b+otherDreieck.b, self.c+otherDreieck.b)

我在Python中做了一个简单的多重继承示例,我无法通过添加类Dreieck的两个对象找到原因,我得到了AttributeError 'Dreieck' object has no attribute 'name'。我想这是因为name属性是私有的,但我认为我在这里继承它:

Shape.__init__(self,center,name)

1 个答案:

答案 0 :(得分:1)

在课堂本身之外,私人名称被破坏了。请参阅Private Variables and Class-local References

您可以使用代码中的错位名称解决此问题。换句话说,请尝试将其引用为self._Shape__name