[英]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.