[英]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}"
使用雙下划線前綴命名變量(例如__somename
)會觸發 python “名稱修改”。 這是為了防止名稱沖突,因此,Python 需要一個特殊的屬性名稱來訪問: _ClassName__somename
而不是__somename
。
例如:
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'
要解決此問題,您應該使用“損壞的”名稱進行訪問,或者重命名變量以刪除雙下划線。
有關更多詳細信息,請參閱有關此主題的詳細 stackoverflow 帖子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.