简体   繁体   English

无法访问从父 class 继承的属性

[英]Can't Access Inherited Attributes from a Parent class

class People:
    #parrent to both Employee and Costumer classes
    def __init__(self, id, name, ssn): #define class People
                                       #self used to accesses attributes and methodes in class
    #set insatance variable
        self.__id = id
        self.__name = name
        self.__ssn = ssn

class Employee(People):
    #Child of Class People
    def __init__(self, id, name, ssn, password):
        People.__init__(self, id, name,ssn)
        self.__password = password

    def __str__(self):
        return f"ID :{self.__id}\nName :{self.__name}\nSSN :{self.__ssn}\nPassword :{self.__password}"

Naming variable with double underscore prefix (eg __somename ) triggers python "name mangling".使用双下划线前缀命名变量(例如__somename )会触发 python “名称修改”。 This is intended to prevent name collision, and as a result, Python requires a special attribute name to access: _ClassName__somename instead of __somename .这是为了防止名称冲突,因此,Python 需要一个特殊的属性名称来访问: _ClassName__somename而不是__somename

For example:例如:

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

>>> Person("x").__name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute '__name'
>>> Person("x")._Person__name
'x'

To fix this you should either use the "mangled" name to access, or rename your variables to remove the double underscore.要解决此问题,您应该使用“损坏的”名称进行访问,或者重命名变量以删除双下划线。

For more details see this detailed stackoverflow post on this topic .有关更多详细信息,请参阅有关此主题的详细 stackoverflow 帖子

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

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