4 回答

TA貢獻2011條經(jīng)驗 獲得超2個贊
從超類繼承后,必須調(diào)用父類的__init__
(構(gòu)造函數(shù))。您可以使用 來獲取對父類的引用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

TA貢獻1818條經(jīng)驗 獲得超8個贊
您可以使用super調(diào)用父類'__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'

TA貢獻1786條經(jīng)驗 獲得超11個贊
為了讓子類訪問父類的方法和屬性,需要在子類的構(gòu)造函數(shù)中調(diào)用父類的構(gòu)造函數(shù)。您可以借助 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)

TA貢獻1942條經(jīng)驗 獲得超3個贊
Python 中的方法與 C++ 或 Java 等真正的 OOP 語言不同。
不存在在類定義中直接聲明屬性以使該屬性自動成為實例屬性的情況:
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
那么如何創(chuàng)建一個對象的屬性呢?好簡單:
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沒有。
有沒有辦法在類定義中規(guī)定/初始化實例的屬性?
幸運的是,有一個特殊的方法__init__(),當您創(chuàng)建類的實例時,它會自動運行,并自動接收剛剛創(chuàng)建的對象作為其第一個參數(shù)(通常稱為this)。
因此,您可以使用此自動填充的參數(shù)為剛剛創(chuàng)建的對象分配一個屬性:
class A:
def __init__(self):
self.an_attribute = 20
self.different_attribute = 50
現(xiàn)在,該類的所有新實例都A將擁有自己的對象屬性 an_attribute和different_attribute(分別用值20和初始化50,這在這里并不重要)。
因此,實例變量不會自動被子類繼承。其他人已經(jīng)解釋了如何繞過它 - 毫不奇怪在內(nèi)置函數(shù)__init__()的幫助下使用子類的方法。super()
添加回答
舉報