Python Static Method
How to define a static method in Python?
Demo:
#!/usr/bin/python2.7 #coding:utf-8 # FileName: test.py # Author: lxw # Date: 2015-07-03 #Inside a class, we can define attributes and methods class Robot: '''Robot class. Attributes and Methods''' population = 0 def __init__(self, name): self.name = name Robot.population += 1 print('(Initialize {0})'.format(self.name)) def __del__(self): Robot.population -= 1 if Robot.population == 0: print('{0} was the last one.'.format(self.name)) else: print('There are still {0:d} robots working.'.format(Robot.population)) def sayHi(self): print('Greetings, my master call me {0}.'.format(self.name)) ''' #The following class method is OK. @classmethod def howMany(cls): #cls is essential. print('We have {0:d} robots.'.format(cls.population)) ''' ''' #The following static method is OK. @staticmethod def howMany(): print('We have {0:d} robots.'.format(Robot.population)) ''' #The following class method is OK. def howMany(cls): #cls is essential. print('We have {0:d} robots.'.format(cls.population)) howMany = classmethod(howMany) ''' #The following static method is OK. def howMany(): print('We have {0:d} robots.'.format(Robot.population)) howMany = staticmethod(howMany) ''' def main(): robot1 = Robot("lxw1") robot1.sayHi() #staticmethod/classmethod 都既可以使用类名访问,也可以使用对象名访问, 但classmethod在定义时需要cls参数 Robot.howMany() robot1.howMany() robot2 = Robot("lxw2") robot2.sayHi() Robot.howMany() robot2.howMany() if __name__ == '__main__': main() else: print("Being imported as a module.")
Differences between staticmethod and classmethod:
classmethod:
Its definition is mutable via inheritance, Its definition follows subclass, not parent class, via inheritance, can be
overridden by subclass. It is important when you want to write a factory method and by this custom attribute(s)
can be attached in a class.
staticmethod:
Its definition is immutable via inheritance. 类似其他语言中的static方法。