我有一個父類和一個子類,其中子類使用 super() 或 Patent 函式從父類繼承初始化變數。但是,我無法在孩子的方法中訪問這些變數。如何獲得它?這是下面的代碼。
class Parent:
def __init__(self, item, model):
self.item = item
self.model = model
class child(Parent):
def __init__(self, item, model):
Parent.__init__(self, item, model)
print(item) # I am able to get this value
def example(self):
value = self.item * 10 # This item is not able to access and throughs an error.
print(value)
呼叫子方法:
child.example()
錯誤:
'child' object has no attribute 'item'
如何將item變數從父類獲取到子類的方法中?
uj5u.com熱心網友回復:
問題是你如何打電話example()
:
child.example()
您正在呼叫類本身example()
的方法;您沒有在. 類本身沒有or屬性。這些是在建構式 ( ) 中設定的。要呼叫建構式,您必須實體化物件的新實體:child
child
self.item
self.model
__init__()
child
c = child(10, 'blah')
現在這c
是 的一個實體child
,您現在可以呼叫example()
該實體:
c.example()
#output: 10
請記住,這是有效的,因為它是對您之前故意創建的類的特定實體c
的參考。指類本身;它不會有任何實體變數,因為一個類只是一個類,它的建構式沒有運行,因為它只在你實體化一個類時運行,而不是在你處理類本身時運行。child
child
self
避免此問題的一種方法是遵守 Python 中的命名標準。類總是應該是CamelCase
,變數都應該是snake_case
。這樣,您可以很容易地看出這child.what_ever()
是在呼叫類的實體上的方法,那Child.blah_blah()
是在呼叫類方法。
有關 Python 命名約定的完整串列,請參見此處:https ://peps.python.org/pep-0008/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487435.html
下一篇:在按鈕上下載檔案單擊jquery