马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#类方法:
class Spam:
numInstance = 0
def __init__(self):
Spam.numInstance += 1
def printNumInstance(aclass):
print('Number of instances:', aclass.numInstance, aclass)
printNumInstance = classmethod(printNumInstance)
class Sub(Spam):
def printNumInstance(aclass):
print('Extra stuff ...', aclass)
Spam.printNumInstance()
printNumInstance = classmethod(printNumInstance)
class Other(Spam):pass
>>> x, y = Sub(), Spam()
>>> x.printNumInstance()
Extra stuff ... <class '__main__.Sub'>
Number of instances: 2 <class '__main__.Spam'>
>>> Sub.printNumInstance()
Extra stuff ... <class '__main__.Sub'>
Number of instances: 2 <class '__main__.Spam'>
>>> y.printNumInstance()
Number of instances: 2 <class '__main__.Spam'>
>>> z = Other()
>>> z.printNumInstance()
Number of instances: 3 <class '__main__.Other'>
#x,z 均继承自Spam,为什么调用Spam.printNumInstance()时,
#aclass返回<class '__main__.Spam'>,而另一个却返回<class '__main__.Other'>
x,z 均继承自Spam,为什么调用Spam.printNumInstance()时,aclass返回<class '__main__.Spam'>,而另一个却返回<class '__main__.Other'> |