creating and naming objects

Maarten van Veen foster at home.nl
Wed Jun 7 16:23:07 EDT 2006


In article <1149696358.065614.76150 at h76g2000cwa.googlegroups.com>,
 "Brian" <bnblazer at gmail.com> 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.
> 
> Thanks,
> Brian

Hi Brian,

If you would do it like this:
Class Student:
    def setName(self, name)
        self.name = name
    def setId(self, id)
        self.id = id


def createStudent():
    foo = Student()
    foo.setName("Brian")
    foo = Student()
    print foo.getName()

You would get an error here, because foo now equals the second Student 
object which has no name. And you can't get to the first one. 
Perhaps you could do something like this.

Class Student:
    def setName(self, name)
        self.name = name
    def setId(self, id)
        self.id = id

listWithStudents = []

def createStudent():
    listWithStudent.append(Student())

Now every student you create is put in the list with students so you can 
access them but don't have to give them names.
You could do something to all of them like this:
for student in listWithStudent:
   student.doSomething()

Or change just one student:
listWithStudent[23].doSomething()  # this is the 24th student though!!!

Hope this is what you're looking for.
Maarten



More information about the Python-list mailing list