0
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'. I suppose it is because the name attribute is private, but I thought I was inheriting it here:

Shape.__init__(self,center,name)
martineau
  • 119,623
  • 25
  • 170
  • 301
jojo
  • 66
  • 9
  • 2
    Why are you invoking name mangling (see e.g. http://stackoverflow.com/q/1301346/3001761)? Why aren't you using `super`? – jonrsharpe Aug 18 '16 at 14:59
  • 3
    Try accessing it via `self.getName()`. Double-underscore prefixed attributes are [not supposed to be accessed outside of their class.](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references) – khelwood Aug 18 '16 at 14:59
  • Thanks for your answer but I think you are overdoing it with your editing – jojo Aug 18 '16 at 15:01
  • jojo: If you don't like the editing, roll back the changes (or manually undo the ones you don't care for). – martineau Aug 18 '16 at 15:08

1 Answers1

1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301