This code...
class Person:
num_of_people = 0
def __init__(self, name):
self.name = name
Person.num_of_people += 1
def __del__(self):
Person.num_of_people -= 1
def __str__(self):
return 'Hello, my name is ' + self.name
cb = Person('Corey')
kb = Person('Katie')
v = Person('Val')
Produces the following error...
Exception AttributeError: "'NoneType' object has no attribute 'num_of_people'" in <bound method Person.__del__ of <__main__.Person object at 0x7f5593632590>> ignored
But this code does not.
class Person:
num_of_people = 0
def __init__(self, name):
self.name = name
Person.num_of_people += 1
def __del__(self):
Person.num_of_people -= 1
def __str__(self):
return 'Hello, my name is ' + self.name
cb = Person('Corey')
kb = Person('Katie')
vb = Person('Val')
The only difference I see is the last variable name is "vb" vs. "v".
I am leaning Python and am working on the OOP stuff now.
__del__
you wouldn't have this problem, and I believe the code you have written is misusing__del__
. In fact in python<3.4 you could easily create some cycles of references so that yournum_of_people
counter is off. – Pushover