classmethod:类方法
staticmethod:静态方法
在python中,静态方法和类方法都是可以通过类对象和类实例对象访问。但是区别是:
- @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 更关注于从类中调用方法,而不是在实例中调用方法,可以用作方法重载, 传入参数cls;类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。(这就要搞清楚python里class也是个真实地存在于内存中的对象,而不是静态语言中只存在于编译期间的类型)。类方法有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。
- 普通对象方法至少需要一个self参数,代表类对象实例。这个也跟其他语言比较像。
- @staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已, 不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。
> > > class a :
@staticmethod
def staticm():
print 'static'
def normalm(self):
print 'nomarl',self
@classmethod
def classm(cls):
print 'class',cls
>>> a1=a()
>>> a1.normalm()
nomarl <__main__.a instance at 0x84dddec>
>>> a1.staticm()
static
>>> a1.classm()
class __main__.a
>>> type(a)
<type 'classobj'>
>>> type(a1)
<type 'instance'>
Example 2:
class A(object):
@classmethod
def cm(cls):
print '类方法cm(cls)调用者:', cls.__name__
@staticmethod
def sm():
print '静态方法sm()被调用'
class B(A):
pass
A.cm()
B.cm()
A.sm()
B.sm()
输出:
类方法cm(cls)调用者: A
类方法cm(cls)调用者: B
静态方法sm()被调用
静态方法sm()被调用
#!/usr/bin/python
#coding:utf-8
#author: gavingeng
#date: 2011-12-03 10:50:01
class Person:
def __init__(self):
print "init"
@staticmethod
def sayHello(hello):
if not hello:
hello='hello'
print "i will sya %s" %hello
@classmethod
def introduce(clazz,hello):
clazz.sayHello(hello)
print "from introduce method"
def hello(self,hello):
self.sayHello(hello)
print "from hello method"
def main():
Person.sayHello("haha")
Person.introduce("hello world!")
#Person.hello("self.hello") #TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)
print "*" * 20
p = Person()
p.sayHello("haha")
p.introduce("hello world!")
p.hello("self.hello")
if __name__=='__main__':
main()
输出:
i will sya haha
i will sya hello world!
from introduce method
********************
init
i will sya haha
i will sya hello world!
from introduce method
i will sya self.hello
from hello method
http://blog.csdn.net/carolzhang8406/article/details/6856817