Yep, using the staticmethod
decorator:
class MyClass(object):
@staticmethod
def the_static_method(x):
print(x)
MyClass.the_static_method(2) # outputs 2
Note that some code might use the old method of defining a static method, using staticmethod
as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3):
class MyClass(object):
def the_static_method(x):
print(x)
the_static_method = staticmethod(the_static_method)
MyClass.the_static_method(2) # outputs 2
This is entirely identical to the first example (using @staticmethod
), just not using the nice decorator syntax.
Finally, use staticmethod
sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.
The following is verbatim from the documentation::
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 as C().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.
Best Answer
You need to do something like:
Depending on what you want to do, a classmethod might be more appropriate:
The difference here is that in the second example, the class itself is passed as the first argument to the method (as opposed to a regular method where the instance is the first argument, or a staticmethod which doesn't receive any additional arguments).
Now to answer your actual question. I'm betting that you aren't finding your method because you have put the class
Person
into a modulePerson.py
.Then:
Alternatively, you might want to import the class Person from the module Person:
This all gets a little confusing as to what is a module and what is a class. Typically, I try to avoid giving classes the same name as the module that they live in. However, this is apparently not looked down on too much as the
datetime
module in the standard library contains adatetime
class.Finally, it is worth pointing out that you don't need a class for this simple example:
Now in another file, import it: