我希望有一些函数在调用我的对象的方法时被调用。这些函数不是由方法定义的——它们稍后会提供给方法(或者可能根本不提供)。有没有比使用更优雅的占位符解决方案: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条经验 获得超2个赞
前段时间问了这个问题,不知道答案。从那以后,我了解到答案是:
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
提交
取消