如何将函数移到类中?python

2024-04-26 13:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个类方法中使用服务函数,其中服务函数是在其他地方定义的。我希望是动态的,这样我就可以在不同的情况下定义不同的函数。我试过了:

def print_a():
    print 'a'

class A:
    func = print_a
    @classmethod
    def apply(cls):
        cls.func()

A.apply()

我收到这个错误:

unbound method print_a() must be called with A instance as first argument (got nothing instead)

有什么办法吗?在


Tags: 方法函数定义def地方错误情况动态
1条回答
网友
1楼 · 发布于 2024-04-26 13:52:53

您可以使用呼叫

def print_a():
    print 'a'

class A:

    func = print_a.__call__

    @classmethod
    def apply(cls):
        cls.func()

A.apply()

输出

^{pr2}$

相关问题 更多 >