classmethod和staticmethod

# coding=utf-8
# python2
 
class A(object):  


    def foo(self, x):  
        print("executing foo(%s,%s)" % (self, x)) 
        print('self:', self) 


    @classmethod  
    def class_foo(cls, x):  
        print("executing class_foo(%s,%s)" % (cls, x)) 
        print('cls:', cls) 


    @staticmethod  
    def static_foo(x): # 不用传递参数self或者cls,跟静态函数形式一样  
    print("executing static_foo(%s)" % x) 

a = A() 
A.class_foo("hei") # executing class_foo(<class '__main__.A'>,hei) # ('cls:', <class '__main__.A'>) 
a.class_foo("ha") # executing class_foo(<class '__main__.A'>,ha) # ('cls:', <class '__main__.A'>) 
A.static_foo("xi") # executing static_foo(xi) a.static_foo("ha") # executing static_foo(ha) 
# 总结:不管是@classmethod还是@staticmethod,两者意义不一样,但是都可以用类对象或者实例对象调用 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值