Create static method dynamically

Peter Otten __peter__ at web.de
Thu Mar 11 18:13:36 EST 2004


Salvatore wrote:

> def hello():
>      print "hello"

> Is there a way of making 'hello' a
> static method of 'myClass ?

>>> class Test:
...     def addStaticMethod(name, func):
...             setattr(Test, name, staticmethod(func))
...     addStaticMethod = staticmethod(addStaticMethod)
...
>>> def hello(): print "hello"
...
>>> t = Test()
>>> t.addStaticMethod("hello", hello)
>>> t.hello()
hello
>>>

Even simpler, if you know the method name beforehand:

>>> Test.world = staticmethod(hello)
>>> t.world()
hello

Peter



More information about the Python-list mailing list