3

I know it's wired to have such a case but somehow I have it:

class foo
 #static method
 @staticmethod
 def test():
 pass
 # class variable
 c = {'name' : <i want to reference test method here.>}

What's the way to it?

Just for the record:

I believe this should be considered as python worst practices. Using static methods is not really pythoish way if ever...

asked Feb 3, 2010 at 18:02
3
  • 1
    You should consider using new-style classes if possible. Commented Feb 3, 2010 at 18:13
  • Also, note that staticmethod should not usually be used. Python has normal functions for this application. Commented Feb 3, 2010 at 18:32
  • that's still not syntactically-valid python Commented Feb 4, 2010 at 11:13

2 Answers 2

5
class Foo:
 # static method
 @staticmethod
 def test():
 pass
 # class variable
 c = {'name' : test }
answered Feb 3, 2010 at 18:05

Comments

4

The problem is static methods in python are descriptor objects. So in the following code:

class Foo:
 # static method
 @staticmethod
 def test():
 pass
 # class variable
 c = {'name' : test }

Foo.c['name'] is the descriptor object, thus is not callable. You would have to type Foo.c['name'].__get__(None, Foo)() to correctly call test() here. If you're unfamiliar with descriptors in python, have a look at the glossary, and there's plenty of docs on the web. Also, have a look at this thread, which seems to be close to your use-case.

To keep things simple, you could probably create that c class attribute just outside of the class definition:

class Foo(object):
 @staticmethod
 def test():
 pass
Foo.c = {'name': Foo.test}

or, if you feel like it, dive in the documentation of __metaclass__.

SilentGhost
322k67 gold badges311 silver badges294 bronze badges
answered Feb 4, 2010 at 10:54

Comments

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.