簡體   English   中英

你如何從一個類的另一個實例調用一個類的函數?

[英]How do you call a function of a class from another instance of a class?

我想通過 class_B 函數從另一個 class_B 提供 class_A 屬性,盡管它似乎想從 class_A 獲取值,即使它尚未定義。 您將如何正確引用 class_B 中的函數?

這是更多洞察力的代碼:

# ============== class_A ==============
class Pepper:
   def __init__ (self):
      self.spice_type = "Pepper"
      self.pepper_flavour = ["sharp","pungent"]
   
   def get_type(self):
      return self.spice_type
   
   def get_flavour(self):
      return self.pepper_flavour

class Salt:
   def __init__ (self):
      self.spice_type = "Salt"
      self.salt_flavour = ["salty","bitter"]
   
   def get_type(self):
      return self.spice_type
   
   def get_flavour(self):
      return self.salt_flavour
# ====================================


# ============== class_B ==============
class Spice:
   def __init__(self,type):
      self.spice_type = type
      self.spice_flavor = type.get_flavour(self)
# ====================================


Pepper_Spice = Spice(Pepper)
print(Pepper_Spice.spice_type,Pepper_Spice.spice_flavor)

Spice 類的構造函數接收類。
所以我們需要做實例化來獲取接收到的類實例的資源作為這段代碼。

# ============== class_B ==============
class Spice:
   def __init__(self,type):
      tinst = type()
      self.spice_type = tinst.spice_type
      self.spice_flavor = tinst.get_flavour()

暫無
暫無

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

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