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

 

转载于:https://www.cnblogs.com/giserliu/p/5785082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值