简体   繁体   English

你如何从一个类的另一个实例调用一个类的函数?

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

I want to give a class_A properties from another class_B through the class_B functions though it seems to want to get the values from the class_A even though it has not yet been defined.我想通过 class_B 函数从另一个 class_B 提供 class_A 属性,尽管它似乎想从 class_A 获取值,即使它尚未定义。 How would you correctly referance the function from class_B?您将如何正确引用 class_B 中的函数?

Here is the code for more insight:这是更多洞察力的代码:

# ============== 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)

The constructer of Spice class receives class. Spice 类的构造函数接收类。
So we need to do instantiation to get the resources of the received class' instance as this code.所以我们需要做实例化来获取接收到的类实例的资源作为这段代码。

# ============== 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