Python中的staticmethod和classmethed作用類似于java中的static方法纯蛾,但是在Python中這兩種方法都可以被實(shí)例化的對(duì)象調(diào)用(不推薦這樣使用)。
classmethed的參數(shù)列表中比staticmethod多一個(gè)cls趴生,即類對(duì)象,Python中一個(gè)類也是一個(gè)實(shí)際存在的對(duì)象,所以可以在classmethed中使用cls繼續(xù)調(diào)用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