![](/img/trans.png)
[英]How to access parent class instance method from child class static method in python?
[英]How to access the init variable obtained from parent class into child method in python?
我有一個父類和一個子類,其中子類使用 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變量從父類獲取到子類的方法中?
問題是您如何調用example()
:
child.example()
您正在調用child
類本身的example()
方法; 您沒有在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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.