转自:https://blog.csdn.net/lihao21/article/details/79762681
不多说,直接上代码示例讲解。
下面三个方法一次为:示例方法、类放大、静态方法。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Kls(object):
def foo(self, x):
print('executing foo(%s,%s)' % (self, x))
@classmethod
def class_foo(cls,x):
print('executing class_foo(%s,%s)' % (cls,x))
@staticmethod
def static_foo(x):
print('executing static_foo(%s)' % x)
if __name__ == '__main__':
ik = Kls()
ik.foo(1)
print(ik.foo)
print('------------------------------------------------')
ik.class_foo(1)
Kls.class_foo(1)
print(ik.class_foo)
print('------------------------------------------------')
ik.static_foo(1)
Kls.static_foo(1)
print(ik.static_foo)
输出如下:
C:\Python36\python3.exe "C:/own/my_exercise/instance and static.py"
executing foo(<__main__.Kls object at 0x02D2DD50>,1)
>
------------------------------------------------
executing class_foo(,1)
executing class_foo(,1)
>
------------------------------------------------
executing static_foo(1)
executing static_foo(1)
如上,三个方法区分如下:
实例方法:
类方法:
静态方法: