如何让 python 中的 class 变量引用同一个 class 的静态方法?

How to let a class variable in python refer to a static method of the same class?

我有一个 class,它有一个 class 变量和一个静态方法,我需要让 class 变量包含对静态方法的回调。

class 看起来像:

class Test(object):
    ref = ???? #this should be my reference

    @staticmethod
    def testmethod(anyparam="bla"):
        print "it works"

我该怎么做?这甚至可能吗?

我正在使用 python 2

编辑: 真实的例子是这样的:

class reg(cmd): 

    bla = {
        'def': [ ... ],
        'rem': [ ...,
            PIPE.return_response(fail_callback=HERE_I_NEED_THE_REF),
            ...
        ]
    }

    @classmethod
    def testmethod(cls, aco):
        print "i want to see this on fail"

关于class创建时引用静态方法的问题,你说的对。 Test 还不在命名空间中,即使您在 testmethod 下定义 ref,静态方法定义魔术也不完整。但是,您可以在创建后修补 class:

class reg(cmd): 

    bla = {
        'def': [ ... ],
        'rem': [ ...,
            PIPE.return_response(fail_callback=HERE_I_NEED_THE_REF),
            ...
        ]
    }

    @classmethod
    def testmethod(cls, aco):
        print "i want to see this on fail"

Test.ref["rem"][??] = PIPE.return_response(fail_callback=Test.testmethod)

如果我对你的问题理解正确,你可以这样做。

class Test(object):
    def __init__(self):
        self.ref = self.testmethod

    @staticmethod
    def testmethod(anyparam="bla"):
        print "it works"

只需在 class 之外定义 class 变量,并遵循其定义的其余部分:

class reg(cmd):
    @classmethod
    def testmethod(cls, aco):
        print "i want to see this on fail"

reg.bla = {
        'def': [ '...' ],
        'rem': [ '...',
            PIPE.return_response(fail_callback=reg.testmethod),
            '...'
        ]
    }