3

我想在类方法中使用服务功能,其中服务功能在其他地方定义。我想是动态的,所以我可以在不同的情况下定义不同的功能。我试过这个:

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)

任何想法如何使它工作?

4

1 回答 1

6

你可以使用通话

def print_a():
    print 'a'

class A:

    func = print_a.__call__

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

A.apply()

输出

a
于 2017-07-20T10:30:54.213 回答