python的类方法和静态方法

本文实例讲述了python的类方法和静态方法。python中实现静态方法和类方法都是依赖于python的修饰器来实现的。

class MyClass:   
    val=100 #类变量;通过类名直接访问  
    def method(self): #实例方法:有self参数  
        print("instance method")   
    @staticmethod   
    def staticMethod(): #静态方法:没有参数  
        print("static method")  
        print MyClass.val 
    @classmethod   
    def classMethod(cls): #类方法:有cls参数  
        print("class method")  
        print cls.val  
  
f=MyClass()  
f.method()  
MyClass.staticMethod()  
print '----------------'  
MyClass.classMethod()

运行结果:

instance method
static method
100
----------------
class method
100

大家注意到普通的实例方法、类方法和静态方法的区别了吗?
实例方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数的。在C++中没有类方法着个概念。。。

class A(object):
    "This is A Class"
    @staticmethod
    def fun1():
        print("Call static method fun1()")
    @classmethod
    def fun2(cls):
        print "Call class method fun2()"
        print "cls.__name__ is",cls.__name__
print A.__name__,A.__doc__
A.fun1();
A.fun2();
运行结果:
A This is A Class
Call static method fun1()
Call class method fun2()
cls.__name__ is A

原文链接:http://www.jb51.net/article/58456.htm



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值