簡體   English   中英

Python:從子類訪問父屬性

[英]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_attributeA的屬性,但不是此類實例的屬性:

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_attributedifferent_attribute (分別用值2050初始化,這里不重要)。


因此,子類不會自動繼承實例變量 其他人已經解釋過,如何繞過它——在super()內置函數的幫助下,在子類的__init__()方法中並不奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM