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. How would you correctly referance the function from 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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.