creating and naming objects
Tim Chase
python.list at tim.thechases.com
Wed Jun 7 12:29:25 EDT 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
True
>>> bar.setName("George")
>>> foo.name #altering "the thing refered to by bar" changes
foo because they both refer to the same object
'George'
>>> foo = Student() # make foo refer to a new student
>>> foo is bar
False
>>> foo.name
''
>>> bar.name
'George'
>>> students = []
>>> students.append(Student())
>>> students.append(Student())
>>> students[0].setName("Alice")
>>> students[1].setName("Bob")
>>> students[0].name
'Alice'
>>> students[1].name
'Bob'
>>> students[0] is students[1]
False
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. :)
-tkc
More information about the Python-list
mailing list