作者:秦风
链接:https://www.zhihu.com/question/49660420/answer/335991541
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
class A(object):
a = 'a'
@staticmethod
def foo1(name):
print 'hello', name
def foo2(self, name):
print 'hello', name
@classmethod
def foo3(cls, name):
print 'hello', name
首先定义一个类A,类A中有三个函数,foo1为静态函数,用@staticmethod装饰器装饰,这种方法与类有某种关系但不需要使用到实例或者类来参与。如下两种方法都可以正常输出,也就是说既可以作为类的方法使用,也可以作为类的实例的方法使用。
a = A()
a.foo1('mamq') # 输出: hello mamq
A.foo1('mamq')# 输出: hello mamq
foo2为正常的
版权声明:本文为weixin_30230059原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。