简体   繁体   English

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

[英]Referencing base class attributes when using 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)

I am doing a simple example of multiple inheritance in Python, and I can't find why by adding two objects of class Dreieck I get an AttributeError 'Dreieck' object has no attribute 'name' . 我正在做一个使用Python进行多重继承的简单示例,但是我找不到通过添加类Dreieck两个对象而得到AttributeError 'Dreieck' object has no attribute 'name' I suppose it is because the name attribute is private, but I thought I was inheriting it here: 我想这是因为name属性是私有的,但是我想我是在这里继承的:

Shape.__init__(self,center,name)

Outside the class itself, private names are mangled. 在班级本身之外,私人名称被修改。 See Private Variables and Class-local References . 请参阅私有变量和类本地引用

You can work around it by using the mangled name in your code. 您可以通过在代码中使用乱码来解决此问题。 In other words try referencing it as self._Shape__name . 换句话说,尝试将其引用为self._Shape__name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM