Skip to main content
 首页 » 编程设计

python之如何继承__del__函数

2025年05月04日18jirigala

我正在阅读 Python Essential Reference 第 4 版。我不知道如何解决以下代码中的问题

class Account(object): 
    num_accounts = 0 
 
    def __init__(self, name, balance): 
        self.name = name 
        self.balance = balance 
        Account.num_accounts += 1 
 
    def __del__(self): 
        Account.num_accounts -= 1 
 
    def deposit(self, amt): 
        self.balance += amt 
 
    def withdraw(self, amt): 
        self.balance -= amt 
 
    def inquire(self): 
        return self.balance 
 
class EvilAccount(Account):     
    def inquire(self): 
        if random.randint(0,4) == 1: 
            return self.balance * 1.1 
        else: 
            return self.balance 
 
ea = EvilAccount('Joe',400) 

如果我理解正确,当程序结束时 ea 对象超出范围并且应该调用继承的 __del__ 函数,对吗?我在 __del__ 中收到一个 'NoneType' 对象没有属性 num_accounts。为什么它不早点在 __init__ 函数中提示?

请您参考如下方法:

来自 the docs :

Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.