staticmethod和classmethod均被作为装饰器,用作定义一个函数为staticmethod还是classmethod
@staticmethod 表示静态方法,不需要实例化类,用类直接调用方法。
@classmethod 表示类方法
-
-
#!/usr/bin/env python
-
# coding=utf-8
-
class Test(object):
-
def instance(self):
-
print "this is instance."
-
@staticmethod
-
def staticmethod(*arg): #括号内没有self,也就无法访问实例变量、类和实例的属性;
-
print "this is staticmethod."
-
print ('static:',arg)
-
@classmethod
-
def classmethod(cls): #括号内没有self,但必须有cls这个参数,能够访问类属性,但不能访问实例属性;
-
print "this is classmethod."
-
print ('class:',cls)
-
if __name__ == "__main__":
-
a = Test() #实例化
-
a.instance() #调用实例方法
-
a.staticmethod() #通过实例调用静态方法
-
Test.staticmethod() #通过类自己调用静态方法
-
a.classmethod() #通过实例调用类方法
-
Test.classmethod() #通过类自身调用类方法
-
-
输出内容:
-
this is instance.
-
this is staticmethod.
-
('static:', ())
-
this is staticmethod.
-
('static:', ())
-
this is classmethod.
-
('class:', <class '__main__.Test'>)
-
this is classmethod.
-
('class:', <class '__main__.Test'>)
-
类直接调用方法会报错:
-
Test.instance()
-
TypeError: unbound method instance() must be called with Test instance as first argument (got nothing instead)
阅读(570) | 评论(0) | 转发(0) |