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

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

Edited 7 Years Ago by mahela007: n/a

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)

Edited 7 Years Ago by Gribouillis: n/a

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.

This question has already been answered. Start a new discussion instead.