creating and naming objects

Diez B. Roggisch deets at nospam.web.de
Wed Jun 7 18:25:14 CEST 2006


Brian wrote:

> I have a question that some may consider silly, but it has me a bit
> stuck and I would appreciate some help in understanding what is going
> on.
> 
> For example, lets say that I have a class that creates a student
> object.
> 
> Class Student:
>     def setName(self, name)
>         self.name = name
>     def setId(self, id)
>         self.id = id
> 
> Then I instantiate that object in a method:
> 
> def createStudent():
>     foo = Student()
>     /add stuff
> 
> Now, suppose that I want to create another Student.  Do I need to name
> that Student something other than foo?  What happens to the original
> object?  If I do not supplant the original data of Student (maybe no id
> for this student) does it retain the data of the previous Student
> object that was not altered?  I guess I am asking how do I
> differentiate between objects when I do not know how many I need to
> create and do not want to hard code names like Student1, Student2 etc.
> 
> I hope that I am clear about what I am asking.

You seem to confuse the terms class and instance. An object is the instance
of a class. You can have as many Students as you like. You just have to
keep a reference around for retrieval. E.g.

students = [Student("student %i" % i) for i in xrange(100)]

will create a list of 100 (boringly named) students.

The 

foo = Student("foo")

will create a Student-object and the name foo refers to it. You are free to
rebind foo to another Student or something completely different.

foo = Student("foo")
foo = 10

When you do so, and no other references to the Student-objects are held, it
will actually disappear - due to garbage collection. 

Diez



More information about the Python-list mailing list