0

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"
asked Mar 26, 2015 at 15:21
6
  • Hmm ok, but how can I reference it then in the "ref" variable? simply writing ref = Test.testmethod does not work Commented Mar 26, 2015 at 15:26
  • How about Test.ref = 'XXX' Commented Mar 26, 2015 at 15:27
  • not possible because in my real use case "ref" is an dict containing lists and i only need to set one element in one list of one dict to the testmethod... Commented Mar 26, 2015 at 15:29
  • 2
    I don't understand then. Can you please provide input and expected output? Commented Mar 26, 2015 at 15:30
  • seems to be not possible because when the dict is defined the class is not completely built. so I cannot refer to those functions because they are not available yet... is this right? Commented Mar 26, 2015 at 15:39

3 Answers 3

1

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)
answered Mar 26, 2015 at 15:35
0

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"
answered Mar 26, 2015 at 15:40
0

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),
 '...'
 ]
 }
answered Mar 26, 2015 at 15:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.