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()
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
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()
class Test(object):
name = 'stephen'
"""docstring for Test"""
def __init__(self, arg=None):
super(Test, self).__init__()
self.arg = arg
def say_hi(self):
print '[1]hello wrold'
@staticmethod
def say_bad():
print '[2]say bad'
print '[3]Test.name:%s'%Test.name //不需要实例化
Test().say_hi() //先要实例化,才能调用say_hi()
@classmethod
def say_good(cls):
print '[4]say good'
print '[5]cls.name:%s'%cls.name //不需要实例化
cls.say_bad() //不需要实例化
cls().say_hi() //先要实例化,才能调用say_hi()
def main():
Test.say_bad()
print "----------------------------------"
Test.say_good()
if __name__ == '__main__':
main()
测试结果:
xxx-xxx:$ python test.py
[2]say bad
[3]Test.name:stephen
[1]hello wrold
----------------------------------
[4]say good
[5]cls.name:stephen
[2]say bad
[3]Test.name:stephen
[1]hello wrold
[1]hello wrold
也可参考:https://www.cnblogs.com/wcwnina/p/8644892.html