类变量(计数器)没有增加 - Python

时间:2016-04-26 19:27:03

标签: oop python-3.x

我有以下代码:

class Account(object):

    counter=0

    def __init__(self, holder, number, balance,credit_line=1500): 
        self.Holder = holder 
        self.Number = number 
        self.Balance = balance
        self.CreditLine = credit_line

    def __del__(self):
        Account.counter -= 1

    def transfer(self, target, amount): 
        if(self.Balance - amount < -self.CreditLine):
            # coverage insufficient
            return False  
        else: 
            self.Balance -= amount 
            target.Balance += amount 
            return True

    def deposit(self, amount): 
        self.Balance = amount 

    def withdraw(self, amount): 
        if(self.Balance - amount < -self.CreditLine):
            # coverage insufficient
            return False  
        else: 
            self.Balance -= amount 
            return True 

    def balance(self): 
        return self.Balance

a1 = Account("abc", 2, 2325.21)

print(Account.counter)

输出显示0.但是,我猜它应该显示为1,因为一个对象已初始化。为什么显示0,以及如何解决?

1 个答案:

答案 0 :(得分:0)

初始化对象时,

counter不会增加。

使用:

def __init__(self, holder, number, balance,credit_line=1500): 
    ...
    Account.counter+=1

析构函数__del__也将从garbe集合中调用,你无法真正预测何时发生这种情况。所以它不是C ++意义上的析构函数。为此目的调用显式对象方法总是更好。