I am relatively new to python. Let me put my doubt in an example:
I create my class object called “person”
class person:
name = ""
age = ""
phones = []
def add_phone(self, number):
self.phones.append(number)
let’s prepare some data to be used later on:
names = ["jhon", "tony", "mike", "peter"]
ages = [34, 36, 23, 75]
phones = [7676, 7677, 7678, 7679]
Let’s enter a for loop:
for i in range(0,4):
new_person = person()
To my understanding, every time the preceding line is executed a new object person is created and called new_person, and any object in the variable new_person from a previous iteration should be destroyed. However this is not the case:
new_person.name = names[i]
new_person.age = ages[i]
new_person.add_phone(phones[i])
print "i= " + str(i)
print "name= "+ new_person.name
print "age= "+ str(new_person.age)
print "phones:"
print new_person.phones
new_person.phones contains the phones that we have added in previous iterations. Does anybody see what I am missing? Does this mean that the object class “person” behaves like a singleton?
The objects are getting created and destroyed as you’d expect. The problem is that
self.phonesbelongs to the class rather than the instance and is therefore shared by all instances ofperson.To fix, change your class like so: