creating and naming objects

Tim Chase python.list at
Wed Jun 7 18:29:25 CEST 2006

> 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 you want to keep the old student around, you have to keep a
reference to it somewhere.  This can be saving the reference 
before you tromp on foo, or make foo a list and keep a list of 
students (which is what it seems like you want to do).

 >>> foo = Student() # foo is a Student
 >>> bar = foo # bar now refers to the same student
 >>> foo is bar
 >>> bar.setName("George")
 >>>  #altering "the thing refered to by bar" changes 
foo because they both refer to the same object
 >>> foo = Student() # make foo refer to a new student
 >>> foo is bar
 >>> students = []
 >>> students.append(Student())
 >>> students.append(Student())
 >>> students[0].setName("Alice")
 >>> students[1].setName("Bob")
 >>> students[0].name
 >>> students[1].name
 >>> students[0] is students[1]

Hopefully the above gives you some ideas as to

-how references work
-how to store multiple students (use a list)

> I hope that I am clear about what I am asking.

I hope I am clear in explaining what I understand that you are 
asking. :)


More information about the Python-list mailing list