>>> type(a1)
example 2:
class a(object):
@classmethod
def cm(cls):
print '类方法cm(cls)调用者:', cls.__name__
@staticmethod
def sm():
print '静态方法sm()被调用'
class b(a):
pass
a.cm()
b.cm()
a.sm()
b.sm()
输出:
类方法cm(cls)调用者: a
类方法cm(cls)调用者: b
静态方法sm()被调用
静态方法sm()被调用
@classmethod与@staticmethod的应用实例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class tclassstatic(object):
obj_num = 0
def __init__(self, data):
self.data = data
tclassstatic.obj_num += 1
def printself(self):
print("self.data: ", self.data)
@staticmethod
def smethod():
print("the number of obj is : ", tclassstatic.obj_num)
@classmethod
def cmethod(cls):
print("cmethod : ", cls.obj_num)
cls.smethod()
def main():
obja = tclassstatic(10)
objb = tclassstatic(12)
objb.printself()
obja.smethod()
objb.cmethod()
print("------------------------------")
tclassstatic.smethod()
tclassstatic.cmethod()
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233输出结果如下:
('self.data: ', 12)
('the number of obj is : ', 2)
('cmethod : ', 2)
('the number of obj is : ', 2)
------------------------------
('the number of obj is : ', 2)
('cmethod : ', 2)
('the number of obj is : ', 2)