'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. 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)
Solution 1:[1]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hochae |
