python - How to inherit __del__ function -
i reading python essential reference 4th ed. , cannot figure out how fix problem in following code
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)
if understand correctly, ea object goes out of scope when program ends , inherited __del__
function should called, correct? receive 'nonetype' object has no attribute num_accounts
in __del__
. why doesn't complain earlier in __init__
function?
from the docs:
warning: due precarious circumstances under
__del__()
methods invoked, exceptions occur during execution ignored, , warning printedsys.stderr
instead. also, when__del__()
invoked in response module being deleted (e.g., when execution of program done), other globals referenced__del__()
method may have been deleted or in process of being torn down (e.g. import machinery shutting down). reason,__del__()
methods should absolute minimum needed maintain external invariants. starting version 1.5, python guarantees globals name begins single underscore deleted module before other globals deleted; if no other references such globals exist, may in assuring imported modules still available @ time when__del__()
method called.
Comments
Post a Comment