What is a static method and when should I use one?

# staticmethod() and classmethod()
# make it easier to call one class method

class ClassA(object):
    def test(this):
        print this
    test = staticmethod(test)

ClassA.test(4)  # 4

class ClassB(object):
    @classmethod
    def test(self, this):
        print this

ClassB.test(4)  # 4

See:
http://www.techexperiment.com/2008/08/21/creating-static-methods-in-python/

That wasn't very clear to me... I thing a worded explanation would be much more useful

A static method is one that can be called without instantiating the class
so

>>> class T(object):
	def test():
		print "HI"

		
>>> T.test()

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    T.test()
TypeError: unbound method test() must be called with T instance as first argument (got nothing instead)
>>>

See how that doesnt work? Well we can make it work by making it into a static method

>>> class T(object):
	@staticmethod
	def test():
		print "HI"

		
>>> T.test()
HI
>>>

So, hopefully that shows what it does :)

A possible use of static methods is to add constructors to a class, like in this example

class Person(object):

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "Person({name}, {age})".format(name=self.name, age=self.age)

    @staticmethod
    def from_sequence(seq):
        name, age = list(seq)
        return Person(name, age)

    @staticmethod
    def from_dict(dic):
        return Person(dic["name"], dic["age"])

if __name__ == "__main__":
    my_tuple = ("John", 32)
    my_dict = {"name":"Fred", "age":55}

    anna = Person("anna", 15)
    john = Person.from_sequence(my_tuple)
    fred = Person.from_dict(my_dict)

    for person in (anna, john, fred):
        print(person)

Thanks a lot Paul T and Gribouillis.. I think this is the ideal type of answer for a forum like this.

Thanks a lot Paul T and Gribouillis.. I think this is the ideal type of answer for a forum like this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.