Is it possible to have static methods in Python so I can call them without initializing a class, like:
ClassName.StaticMethod ( )
-
Yes, check out the staticmethod decorator:
>>> class C: ... @staticmethod ... def hello(): ... print "Hello World" ... >>> C.hello() Hello World -
Yep, using the staticmethod decorator
class MyClass(object): @staticmethod def the_static_method(x): print x MyClass.the_static_method(2) # outputs 2
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, ...): ...The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.
It can be called either on the class (such as
C.f()) or on an instance (such asC().f()). The instance is ignored except for its class.Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().
For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
New in version 2.2.
Changed in version 2.4: Function decorator syntax added.
S.Lott : +1: Quote the documentation (^_^): @dbr: Can I call one static method from another? -
You don"t really need to use the @staticmethod decorator. Just declaring a method (that doesn't expecet the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)
Mostly, you just use functions though...
0 comments:
Post a Comment