簡體   English   中英

如何將從父類獲得的init變量訪問到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.itemself.model屬性。 這些是在構造函數( __init__() )中設置的。 要調用構造函數,您必須實例child對象的新實例:

c = child(10, 'blah')

現在cchild的一個實例,您現在可以在該實例上調用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.

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