我希望有一些函數在調用我的對象的方法時被調用。這些函數不是由方法定義的——它們稍后會提供給方法(或者可能根本不提供)。有沒有比使用更優雅的占位符解決方案:class MyObj: def __init__(self): self.bind = self.donothing #variable that may or may not be set by the parent def func(self): """Function to be called by the parent""" self.bind() ## do stuff @staticmethod def donothing(): pass
2 回答

翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
您可以執行以下操作:
class MyObj:
def __init__(self):
self.bind = None
def func(self):
"""Function to be called by the parent"""
if self.bind:
self.bind()
## do stuff
def define_function(self, f):
self.bind = f
與其他對象一樣,函數可以用作方法的參數。只需在沒有值的情況下初始化變量并使用設置器為其分配一個值。

DIEA
TA貢獻1820條經驗 獲得超3個贊
前段時間問了這個問題,不知道答案。從那以后,我了解到答案是:
class MyObj:
def __init__(self):
self.bind = lambda *a, **b: ()
def func(self):
"""Function to be called by the parent"""
self.bind()
## do stuff
添加回答
舉報
0/150
提交
取消