为了账号安全,请及时绑定邮箱和手机立即绑定

如何让一个函数在不定义的情况下什么都不做?

如何让一个函数在不定义的情况下什么都不做?

手掌心 2022-01-18 13:45:54
我希望有一些函数在调用我的对象的方法时被调用。这些函数不是由方法定义的——它们稍后会提供给方法(或者可能根本不提供)。有没有比使用更优雅的占位符解决方案: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

与其他对象一样,函数可以用作方法的参数。只需在没有值的情况下初始化变量并使用设置器为其分配一个值。


查看完整回答
反对 回复 2022-01-18
?
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


查看完整回答
反对 回复 2022-01-18
  • 2 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信