本文实例讲述了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