class Test(object):
"""docstring for Test"""
def __init__(self, arg=None):
super(Test, self).__init__()
self.arg = arg
def say_hi(self):
print 'hello wrold'
def main():
test = Test() //1. 首先实例化test类
test.say_hi() //2. 再调用类的方法
if __name__ == '__main__':
main()
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
class Test(object):
"""docstring for Test"""
def __init__(self, arg=None):
super(Test, self).__init__()
self.arg = arg
def say_hi(self):
print 'hello wrold'
@staticmethod
def say_bad():
print 'say bad'
@classmethod
def say_good(cls):
print 'say good'
def main():
test = Test()
test.say_hi()
Test.say_bad() //直接类名.方法名()来调用
Test.say_good() //直接类名.方法名()来调用
if __name__ == '__main__':
main() @staticmethod或@classmethod的区别
类的普通方法,地一个参数需要self参数表示自身。
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
以上就是装饰器@staticmethod和@classmethod有什么区别的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于装饰器@staticmethod和@classmethod有什么区别的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did80709