在__init__中定义成员函数

问题描述 投票:0回答:1

是否可以在init方法内的python类中定义成员函数?

我在想类似setattr或通过lambda的东西

class Engine(Base):
    def __init__(self):
        super(Engine, self).__init__(self)
        self.__class__.__call__ = lambda self, x: x

不起作用,但是

 class Engine(Base):
        def __init__(self):
            self.__class__.__call__ = lambda self, x: x
            super(Engine, self).__init__(self)

是,为什么呢?

python class init
1个回答
0
投票

是,可以。像这样:

class Engine(Base):
    def __init__(self):
        super().__init__()
        self.__class__.__call__ = lambda self, x: x

a = Engine()
print(a(42))  # it prints 42
© www.soinside.com 2019 - 2024. All rights reserved.