Artium
Artium

Reputation: 5329

How to store a method in a static variable?

I was looking for a way to dynamically add static methods to a python class.

My attempt was as following:

class C(object):
    a = None

k = 2
C.a = lambda x: k*x
print C.a(2)

Unfortunately, I get an error saying that C instance is required as the first argument to a. Effectively, python thinks that a is an instance method of class C and not a class method.

What are the reasons for this? How can I overcome the problem?

Upvotes: 1

Views: 136

Answers (1)

senderle
senderle

Reputation: 151077

Use staticmethod:

>>> C.a = staticmethod(lambda x: k*x)
>>> print C.a(2)
4

Upvotes: 5

Related Questions