Issue with making object callable in python

后端 未结 3 1570
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 06:31

I wrote code like this

>>> class a(object):
        def __init__(self):
            self.__call__ = lambda x:x

>>> b = a()

I

3条回答
  •  伪装坚强ぢ
    2021-02-05 07:20

    __call__ needs to be defined on the class, not the instance

    class a(object):
        def __init__(self):
            pass
        __call__ = lambda x:x
    

    but most people probably find it more readable to define the method the usual way

    class a(object):
        def __init__(self):
            pass
        def __call__(self):
            return self
    

    If you need to have different behaviour for each instance you could do it like this

    class a(object):
        def __init__(self):
            self.myfunc = lambda x:x
    
        def __call__(self):
            return self.myfunc(self)
    

提交回复
热议问题