python中的静态方法和类方法

静态方法实际上就是普通函数,定义形式是在def行前加修饰符@staticmethod,只是由于某种原因需要定义在类里面。静态方法的参数可以根据需要定义,不需要特殊的self参数。可以通过类名或者值为实例对象的变量,已属性引用的方式调用静态方法

类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。

 1 ##coding:utf-8
 2 class TestClassMethod(object):
 3 
 4     METHOD = 'method hoho'
 5 
 6     def __init__(self):
 7         self.name = 'leon'
 8 
 9     def test1(self):
10         print 'test1'
11         print self
12 
13     @classmethod
14     def test2(cls):
15         print cls
16         print 'test2'
17         print TestClassMethod.METHOD
18         print '----------------'
19 
20     @staticmethod
21     def test3():
22         print TestClassMethod.METHOD
23         print 'test3'
24 
25 
26 a = TestClassMethod()
27 a.test1()
28 a.test2()
29 a.test3()
30 TestClassMethod.test3()
test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3

实例方法隐含的参数为类实例,而类方法隐含的参数为类本身。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。

在贴一例,供参考:

 1 class TestClassMethod(object):
 2 
 3     METHOD = 'method hoho'
 4 
 5     def __init__(self):
 6         self.name = 'leon'
 7 
 8     def test1(self):
 9         print 'test1'
10         print self
11 
12     @classmethod
13     def test2(cls):
14         print cls
15         print 'test2'
16         print TestClassMethod.METHOD
17         print '----------------'
18 
19     @staticmethod
20     def test3():
21         print TestClassMethod.METHOD
22         print 'test3'
23 
24 
25 a = TestClassMethod()
26 a.test1()
27 a.test2()
28 a.test3()
29 TestClassMethod.test3()
test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3

 

posted @ 2016-08-18 19:03  whgiser  阅读(7429)  评论(0编辑  收藏  举报