4
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by mahela007
0

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

Edited by mahela007: n/a

0

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 :)

0

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 by Gribouillis: n/a

0

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.