Calling static method in python

Sadiksha Gautam picture Sadiksha Gautam · Aug 1, 2012 · Viewed 96.3k times · Source

I have a class Person and a static method in that class called call_person:

class Person:
    def call_person():
        print "hello person"

In the python console I import the class Person and call Person.call_person(). But it is giving me error that says 'module' object has no attribute 'call_person'. Can anyone please let me know why I am getting this error?

Answer

mgilson picture mgilson · Aug 1, 2012

You need to do something like:

class Person:
    @staticmethod
    def call_person():
        print "hello person"

# Calling static methods works on classes as well as instances of that class
Person.call_person()  # calling on class
p = Person()
p.call_person()       # calling on instance of class

Depending on what you want to do, a classmethod might be more appropriate:

class Person:
    @classmethod
    def call_person(cls):
        print "hello person",cls

p = Person().call_person() # using classmethod on instance
Person.call_person()       # using classmethod on class

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 module Person.py.

Then:

import Person  # Person class is available as Person.Person
Person.Person.call_person() # this should work
Person.Person().call_person() # this should work as well

Alternatively, you might want to import the class Person from the module Person:

from Person import Person
Person.call_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 a datetime class.

Finally, it is worth pointing out that you don't need a class for this simple example:

# Person.py
def call_person():
    print "Hello person"

Now in another file, import it:

import Person
Person.call_person() # 'Hello person'