473,388 Members | 1,492 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

creating and naming objects

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

Jun 7 '06 #1
9 1403
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
Jun 7 '06 #2
> 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


Jun 7 '06 #3
Brian wrote:
[...]
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.
[...]

Just return your Student object from createStudent() and put it in a
list. For example:

all_students = []

for i in range(10):
one_student = createStudent()

# Do what you want with one_student here

all_students.append(one_student)

print all_students
BTW: Why don't you use a constructor to create Student objects?

Bye,
Dennis
Jun 7 '06 #4
Thank you all for your response. I think that I am getting it. Based
on those responses, would I be correct in thinking that this would be
the way to initialize my Student object and return the values?

class Student:
def __init__(self, name, id):
self.name = name
self.id = id

def getName(self):
return self.name

def getId(self):
return self.id

Additionally, correct me if I am wrong but I can recycle:

foo = Student()

And doing so will just create a new instance of Student (with whatever
attributes it is given) and the original foo is gone?

Thanks for your help and patience. After reading my original post and
then this one, I could see that it may look suspiciously like a home
work assignment. Trust me it's not. The student example just seemed
like a good fit to discuss this.

Thanks again,
Brian

Jun 7 '06 #5
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

Jun 7 '06 #6

Brian wrote:
Thank you all for your response. I think that I am getting it. Based
on those responses, would I be correct in thinking that this would be
the way to initialize my Student object and return the values?

class Student:
def __init__(self, name, id):
self.name = name
self.id = id

def getName(self):
return self.name

def getId(self):
return self.id

Additionally, correct me if I am wrong but I can recycle:

foo = Student()

And doing so will just create a new instance of Student (with whatever
attributes it is given) and the original foo is gone?

Thanks for your help and patience. After reading my original post and
then this one, I could see that it may look suspiciously like a home
work assignment. Trust me it's not. The student example just seemed
like a good fit to discuss this.

Thanks again,
Brian


Here's a page from the Python tutorial wiki which may be helpful to
you:

http://pytut.infogami.com/node11-baseline.html

It's an introduction to classes which, appositely, uses a Student class
as an example. Still a work in progress. Feel free to leave a comment
if you find it helpful or not - your input would be very much valued.
(Note the StudentTracker class).

Gerard

Jun 7 '06 #7
Brian wrote:
Thank you all for your response. I think that I am getting it. Based
on those responses, would I be correct in thinking that this would be
the way to initialize my Student object and return the values?

class Student:
Do yourself a favour: use new-style classes

class Student(object):
def __init__(self, name, id):
self.name = name
self.id = id
ok until here.
def getName(self):
return self.name

def getId(self):
return self.id
These to getters are totally useless in Python. Python doesn't have
access restrictors [1], so you can directly access the attributes.
Python also has support for computed attributes (looks like an ordinary
attribute but is accessed thru a getter/setter), so there's no problem
wrt/ encapsulation. Just get rid of these two methods and you'll be fine.

[1] it's on purpose - we prefer to use conventions like using
_names_starting_with_a_leading_underscore to denote implementation stuff
that should not be accessed by client code.
Additionally, correct me if I am wrong but I can recycle:

foo = Student()
This won't work - will raise a TypeError. You defined Student.__init__()
to take 2 mandatory parameters name and id,so you must pass them at call
time.

FWIW, you would have noticed this just by trying it into your Python
shell. The interactive Python shell is a very valuable tool. It makes
exploring APIs and testing ideas a breeze, with immediate feedback. It
is one of the things that makes Python so easy and usable (not that it's
a Python invention - but it's a GoodThing(tm) Python have it).
And doing so will just create a new instance of Student (with whatever
attributes it is given) and the original foo is gone?
Yes. Or more exactly, the identifier 'foo' will refer to the newly
created Student object, and if there are no other references to the
object previously pointed by 'foo', it will be disposed of...
Thanks for your help and patience. After reading my original post and
then this one, I could see that it may look suspiciously like a home
work assignment. Trust me it's not.


It could have been homework, this is not a problem - as long as you
effectively tried to do your homework by yourself, and only ask for help
when stuck. FWIW, in this job, knowing when and how to ask for help is
as important as knowing how to first try to solve the problem oneself !-)

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 7 '06 #8
In article <11*********************@h76g2000cwa.googlegroups. com>,
"Brian" <bn******@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
Jun 7 '06 #9

Maarten van Veen wrote:
<snip>

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


This is of great help. Thank you,
Brian

Jun 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: VK | last post by:
09/30/03 Phil Powell posted his "Radio buttons do not appear checked" question. This question led to a long discussion about the naming rules applying to variables, objects, methods and properties...
8
by: Lance | last post by:
I've been teaching myself C# for a few months now and I have a concept problem. I know how to instantiate an object from a class I’ve created, but now I want to retrieve and store data in a...
4
by: kd | last post by:
Hi All, What is the naming convention for objects? I checked the MSDN and found naming conventions for class members, etc; but could not find information on the objects. It would be great if...
6
by: dm1608 | last post by:
I'm relatively new to ASP.NET 2.0 and am struggling with trying to find the best naming convention for the BAL and DAL objects within my database. Does anyone have any recommendations or best...
8
by: Daz | last post by:
Hi all! This question may hopefully spark a little debate, but my problem is this: I am sure it's not just me who struggles to think up names for variables. Obviously, thinking up a name...
3
by: rsine | last post by:
I have searched around a little and have yet to find a naming convention for the string builder object. I really do not want to use "str" since this is for string objects and thus could be...
35
by: Smithers | last post by:
Is it common practise to begin the name of form classes with "frm" (e.g., frmOneForm, frmAnotherForm). Or is that generally considered an outdated convention? If not "frm" what is a common or...
6
by: RSH | last post by:
Hi, i have a situation where I need to dynamically create objects in a loop. My question surrounds intantiation naming in such a scenerio. Below is a snippet that is basically hardcoding each...
9
by: BillCo | last post by:
I'm coming from a MS Access background and so I'm very used to and comfortable with the hungarian (Leszynski et al) naming conventions. However, I'm getting started into my first SQL Server...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.