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

我希望有一些函数在调用我的对象的方法时被调用。这些函数不是由方法定义的——它们稍后会提供给方法(或者可能根本不提供)。有没有比使用更优雅的占位符解决方案:


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


手掌心
浏览 114回答 2
2回答

翻过高山走不出你

您可以执行以下操作: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

前段时间问了这个问题,不知道答案。从那以后,我了解到答案是:class MyObj:    def __init__(self):        self.bind = lambda *a, **b: ()    def func(self):        """Function to be called by the parent"""        self.bind()        ## do stuff
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python