Python中的staticmethod和classmethed作用类似于java中的static方法,但是在Python中这两种方法都可以被实例化的对象调用(不推荐这样使用)。
classmethed的参数列表中比staticmethod多一个cls,即类对象,Python中一个类也是一个实际存在的对象,所以可以在classmethed中使用cls继续调用staticmethod方法。
代码示例:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 'zhonghua'
# filename: 'hello_world'
# create: '2016/3/27'
# version: 1.0
class HelloWorld:
def __init__(self):
print 'Init HelloWorld.'
@staticmethod
def hello_static(name):
print 'hello_static(): Hello %s' %name
print
@classmethod
def hello_class(cls, name):
print 'hello_class(): Hello %s' %name
print 'Now call hello_static():'
cls.hello_static(name)
print
def hello_world(self, name):
print 'hello_world(): Hello %s' %name
print
if __name__ == '__main__':
HelloWorld.hello_static('static')
HelloWorld.hello_class('class')
hw = HelloWorld()
hw.hello_world('common')
hw.hello_static('hw.static')
hw.hello_class('hw.class')
输出:
hello_static(): Hello static
hello_class(): Hello class
Now call hello_static():
hello_static(): Hello class
Init HelloWorld.
hello_world(): Hello common
hello_static(): Hello hw.static
hello_class(): Hello hw.class
Now call hello_static():
hello_static(): Hello hw.class