1
我正在製作類似的類,但功能不同,具體取決於類的用途。在Python中添加__init __()方法
class Cup:
def __init__(self, content):
self.content = content
def spill(self):
print(f"The {self.content} was spilled.")
def drink(self):
print(f"You drank the {self.content}.")
Coffee = Cup("coffee")
Coffee.spill()
> The coffee was spilled.
但是,在對象的初始化過程中是否知道杯子是否會溢出或喝掉。如果杯子很多,則不需要所有人都具有這兩種功能,因爲只有其中一個會被使用。我如何在初始化過程中添加一個函數?
直覺上應該是這樣的,但是這顯然沒有奏效:
def spill(self):
print(f"The {self.content} was spilled.")
class Cup:
def __init__(self, content, function):
self.content = content
self.function = function
Coffee = Cup("coffee", spill)
Coffee.function()
> The coffee was spilled