2017-07-24 26 views
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 

回答

2

如果您在Python中創建一個類的方法例如

class A 
    def method(self, param1, param) 

這將確保當你調用A().method(x,y)它填補了self參數與A的情況下當您嘗試指定class之外自己的方法,那麼你也必須確保綁定做得好。

import functools 
class Cup: 
    def __init__(self, content, function): 
     self.content = content 
     self.function = functools.partial(function, self)