creating and naming objects
Steve Holden
steve at holdenweb.com
Wed Jun 7 12:33:39 EDT 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()
Of course here you'd need an argument to correspond to the student
name, but we'll overlook that.
> /add stuff
>
This actually looks like a Student "factory function", though I have
reservations about it (see below).
> 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
>
Presumably your definition of createStudent() ends with something like
return foo
otherwise the created Student object has no references once the function
complete, and will therefore become non-referenced garbage immediately.
Assuming that createStudent() does indeed return the created Student
instance then you would use it like this:
s1 = createStudent()
...
s2 = createStudent()
and so on. Of course there's nothing to stop you creating lists of
students or dicts of students either. Objects don't really "have names"
in Python, it's better to think of names being references to objects.
Each object can be referenced by zero, one or more names, but references
can also be stored in the items of container objects.
A point you don't appear to have thought of, though, is that all the
functionality implemented in your createStudent() function could just as
easily become part of the Student.__init__() method. Then there's no
need to create a factory function at all - the __init__() method just
initialises each newly-created instance before you get your hands on it.
Then your code would be more like
s1 = Student()
...
s2 = Student()
and so on. Plus, of course, the __init__() method can take arguments if
they are needed to initialize the object successfully. So I'm not really
sure quite what createStudent() is for.
Hope this rambling helps at least a bit.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list