[英]Python: access a parent attribute from the child class
在 Python 中,我有以下代碼作為測驗問題出現:
class Big_Cat:
def __init__(self):
self.x = "dangerous"
class Cat(Big_Cat):
def __init__(self):
self.y = "quiet"
new_cat = Cat()
print(new_cat.x, new_cat.y)
由於 cat 類繼承自BigCat
類,因此它也應該可以訪問變量x
。 那么為什么它會在打印屏幕行上拋出錯誤。 new_cat
如何才能從父級訪問變量x
?
從超類繼承后,必須調用父類的__init__
(構造函數)。 您可以使用super()
獲取對父類的引用。
下面是一個例子:
class Big_Cat:
def __init__(self):
self.x = "dangerous"
class Cat(Big_Cat):
def __init__(self):
super().__init__()
self.y = "quiet"
new_cat = Cat()
print(new_cat.x, new_cat.y)
輸出:
dangerous quiet
您可以使用super
來調用父類' __init__
In [1829]: class Big_Cat:
...: def __init__(self):
...: self.x = "dangerous"
...:
...: class Cat(Big_Cat):
...: def __init__(self):
...: super(Cat, self).__init__()
...: self.y = "quiet"
...:
...: new_cat = Cat()
In [1830]: new_cat.x
Out[1830]: 'dangerous'
您需要在子類的構造函數中調用父類的構造函數,以便子類訪問父類的方法和屬性。 您可以在 super() 方法的幫助下做到這一點。
class Big_Cat:
def __init__(self):
self.x = "dangerous"
class Cat(Big_Cat):
def __init__(self):
super().__init__()
self.y = "quiet"
new_cat = Cat()
print(new_cat.x, new_cat.y)
在 Python 中,有一種與真正的 OOP 語言(如 C++ 或 Java)不同的方法。
沒有在類定義中以直接方式聲明屬性這樣的事情,以便該屬性將自動成為實例的屬性:
class A:
an_attribute = 0
an_attribute
是類A
的屬性,但不是此類實例的屬性:
a = A() # an instance of the class A
print(a.an_attribute) # 0 - so IS the an_attribute an instance's attribute?
似乎an_attribute
是實例的屬性,但是......
A.an_attribute = 100 # changing the value of a CLASS attribute
print(a.an_attribute) # 100; so it is NOT the independent OBJECT 's attribute
那么如何創建對象的屬性呢? 好簡單:
a.an_attribute = 200 # creating an OBJECT's attribute
print(a.an_attribute) # 200 — the OBJECT's attribute, independent of a CLASS' one
print(A.an_attribute) # 100 — the CLASS attribute
從這一刻起,對象a
就有了自己的屬性,不同於同名的類屬性。
這意味着同一類的不同實例不僅可能具有相同屬性的不同值,甚至可能具有完全不同的屬性:
b = A()
b.different_attribute = 500
很奇怪的情況:
a
具有屬性an_attribute
,但同一類的對象b
沒有,b
具有屬性different_attribute
,但對象a
沒有。有沒有辦法在類定義中規定/初始化實例的屬性?
幸運的是,有一個特殊的方法__init__()
,當你創建一個類的實例時它會自動運行,並且它會自動接收剛剛創建的對象作為它的第一個參數(通常命名為this
)。
因此,您可以使用此自動填充的參數為剛創建的對象分配一個屬性:
class A:
def __init__(self):
self.an_attribute = 20
self.different_attribute = 50
現在,類A
所有新實例都將擁有自己的對象屬性an_attribute
和different_attribute
(分別用值20
和50
初始化,這里不重要)。
因此,子類不會自動繼承實例變量。 其他人已經解釋過,如何繞過它——在super()
內置函數的幫助下,在子類的__init__()
方法中並不奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.