Python中classmethod与staticmethod区别

时间:2014-05-19 16:32:15   收藏:0   阅读:263

classmethod:类方法
staticmethod:静态方法

在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:

Example 1:

>>> 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()被调用.

更多:http://www.zhihu.com/question/20021164

Python中classmethod与staticmethod区别,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!