Python inheritance returns attribute error

后端 未结 3 490
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题