Python inheritance returns attribute error

后端 未结 3 494
死守一世寂寞
死守一世寂寞 2021-01-06 12:52

Just starting out Python, i\'m a fan of Derek Banas and have been following a tutorial and I\'m stuck with a bit of code.

class Dog(Animal):
    __owner = \"         


        
相关标签:
3条回答
  • 2021-01-06 13:18

    The child class itself doesn't have the attribute, use this instead.

    return super(Dog, self).toString() + "His owner is {}".format(self.__owner)
    
    0 讨论(0)
  • 2021-01-06 13:20

    Change your function code

    from

    def toString(self):
            return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
            self.__name,
            self.__height,
            self.__weight,
            self.__sound,
            self.__owner)
    

    to

    def toString(self):
            return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
            self.get_name(),
            self.get_height(),
            self.get_weight(),
            self.get_sound(),
            self.get_owner())
    
    0 讨论(0)
  • 2021-01-06 13:22

    Your Animal class is using Name Mangling. From documentation -

    Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

    (Emphasis mine)

    Hence , after your Animal class got defined any name such as __name would have changed to _Animal__name , etc. You would also need to access them alike that in your Dog class.

    But I don't think you actually need to use Name Mangling , you should avoid using the two leading underscores, if you didn't mean for Name Mangling to happen.

    0 讨论(0)
提交回复
热议问题