I have a class that has a class variable and a static method and I need to let the class variable contain a callback to the static method.
The class looks like:
class Test(object):
ref = ???? #this should be my reference
@staticmethod
def testmethod(anyparam="bla"):
print "it works"
How can I do this? Is this even possible?
I am using python 2
EDIT: The real example is this:
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"
3 Answers 3
You are right about the problems of referencing the static method during class creation. Test
isn't in the namespace yet, and even if you define ref
below testmethod
, the static method definition magic isn't complete. You can, however, patch the class after its created:
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)
If I understand your question correctly, you can do this.
class Test(object):
def __init__(self):
self.ref = self.testmethod
@staticmethod
def testmethod(anyparam="bla"):
print "it works"
Just define the class variable outside the class following the rest of its definition:
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),
'...'
]
}
Test.ref = 'XXX'