class Account(object):
num_accounts = 0
派尘 def __init__(self, name, balance):
self.name = name
self.balance = balance
没羡薯 Account.num_accounts += 1
print '__init__:',Account.num_accounts
def __del__(self):
self.__class__.num_accounts -= 1
print '__del__:',self.__class__.num_accounts
枯者def deposit(self, amt):
self.balance = self.balance + amt
print self.balance
def withdraw(self, amt):
self.balance = self.balance - amt
print self.balance
def inquiry(self):
return self.balance
print self.balance
a = Account("Guido", 1000.00)
print 'a:',a
b = Account("Guiio", 10.00)
print 'b:',b
使用域变量时,可以通过self的__class__域来引用
与python的内存回收按照字典先后顺序有关
把__del__中的Account.num_accounts换成self.__class__.num_accounts,将不会出错!
运行结果如下:
__init__: 1
a: <__main__.Account object at 0x023EFBD0>
__init__: 2
b: <__main__.Account object at 0x023EFBB0>
__del__: 1
__del__: 0