object name from a variable.

This is the place for queries that don't fit in any of the other categories.

object name from a variable.

Postby sheffieldlad » Mon Apr 15, 2013 8:26 pm

Hi all,

I'm trying to create a lot of objects from a class and give all of them a different name something like person1 through person99 for 100 objects for example.

The only way I can think of doing this is by passing the object names as a variable when each object is created something like this...


Code: Select all
a = "person"
c = 1
while c <100:
    classname = a+c
    newobject = classname
    newobject = person(cage,cjob,csex,cfname,clname)
c +=1


This obviously won't work because I can't concatenate a str and an int.

This doesn't work either...

Code: Select all
a = "person"
c = 1
while c <100:
    classname = a+str(c)
    newobject = classname
    newobject = person(cage,cjob,csex,cfname,clname)
c +=1

The code runs with no errors but no objects are created from my class.

Can anyone advise please?

TIA,

-Paul.
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK

Re: object name from a variable.

Postby Yoriz » Mon Apr 15, 2013 8:42 pm

Easiest way is just to use a dictionary to store them and alter the key by using string formatting.

Code: Select all
people = {}
for index in xrange(1, 101):
    people['Person{0}'.format(index)] = person(cage,cjob,csex,cfname,clname)
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 781
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: object name from a variable.

Postby sheffieldlad » Mon Apr 15, 2013 8:44 pm

Yoriz wrote:Easiest way is just to use a dictionary to store them and alter the key by using string formatting.

Code: Select all
people = {}
for index in xrange(1, 101):
    people['Person{0}'.format(index)] = person(cage,cjob,csex,cfname,clname)



Many thanks Yoriz, I'll give that a go and have a read about string formatting so I understand it a little better.

-Paul
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK

Re: object name from a variable.

Postby sheffieldlad » Mon Apr 15, 2013 8:51 pm

I still can't get it to work.

I'll post my full code (Probably should have done that in the first place....)

The code runs but no objects are created.

Code: Select all
import random
from random import choice

fnames = ['andrew', 'paul', 'matthew', 'mark', 'luke', 'john']
sexes = ['male', 'female']
jobs = ['driver', 'postman', 'builder', 'computer programmer', 'labourer', 'priest', 'office worker', 'receptionist', 'lawyer', 'drug dealer', 'policeman', 'fireman', 'doctor']
lnames = ['smith', 'brown', 'jones', 'white', 'dawson', 'waller', 'gray', 'king', 'wallace', 'terry', 'bibby']

population = 0

class person():
    def __init__(self,age,job,sex,fname,lname):

        self.age=age
        self.job=job
        self.sex=sex
        self.fname=fname
        self.lname=lname
    population +=1

print "Spawning population. Please wait."   
people = {}
for index in xrange(1, 101):
   
    cage = random.randint(1, 90)
    cjob = choice(jobs)
    csex = choice(sexes)
    cfname = choice(fnames)
    clname = choice(lnames)
   
    people['Person{0}'.format(index)] = person(cage,cjob,csex,cfname,clname)
   


am I right in thinking the line:

Code: Select all
population +=1


Should run each time an instance of the class is created?

TIA

-Paul
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK

Re: object name from a variable.

Postby Yoriz » Mon Apr 15, 2013 9:12 pm

You code is creating the objects you just haven't printed them to see that they are there.
Class names should start with a capital letter.
To get the population you can just get the 'len' of the people dictionary.

Code: Select all
import random
from random import choice

fnames = ['andrew', 'paul', 'matthew', 'mark', 'luke', 'john']
sexes = ['male', 'female']
jobs = ['driver', 'postman', 'builder', 'computer programmer', 'labourer',
        'priest', 'office worker', 'receptionist', 'lawyer', 'drug dealer',
        'policeman', 'fireman', 'doctor']
lnames = ['smith', 'brown', 'jones', 'white', 'dawson', 'waller', 'gray',
          'king', 'wallace', 'terry', 'bibby']


class Person(object):
    def __init__(self, age, job, sex, fname, lname):

        self.age = age
        self.job = job
        self.sex = sex
        self.fname = fname
        self.lname = lname

    def __repr__(self):
        string = 'Person(age: {0}, job: {1}, sex: {2}, fname{3}, lname: {4})'
        return string.format(self.age, self.job, self.sex, self.fname,
                             self.lname)

print "Spawning population. Please wait."
people = {}
for index in xrange(1, 101):

    cage = random.randint(1, 90)
    cjob = choice(jobs)
    csex = choice(sexes)
    cfname = choice(fnames)
    clname = choice(lnames)

    people['Person{0}'.format(index)] = Person(cage, cjob, csex, cfname,
                                               clname)


print 'population: {0}'.format(len(people))
for key, value in people.iteritems():
    print key, value
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 781
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: object name from a variable.

Postby sheffieldlad » Mon Apr 15, 2013 9:34 pm

Many thanks but I have one more question.

I envisaged 100 instances of my class which I could easily change some of the properties such as job or age by doing something like this in the IDE.

>>>> Person9.age
21
>>>> Person9.age = 22
>>>> Person9.age
22

Is it possible to do it that way instead of altering values in a dictionary?

Thanks again,

-Paul
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK

Re: object name from a variable.

Postby Yoriz » Mon Apr 15, 2013 9:49 pm

I don't think you really want 100 people floating around your namespace, if you keep them in a dict or a list you can iterate over them and get to them by key or index.

This might be a bit closer to how you want it, you can choose to store them in a dict or a list, it depends on your requirements.

Code: Select all
import random
from random import choice

fnames = ['andrew', 'paul', 'matthew', 'mark', 'luke', 'john']
sexes = ['male', 'female']
jobs = ['driver', 'postman', 'builder', 'computer programmer', 'labourer',
        'priest', 'office worker', 'receptionist', 'lawyer', 'drug dealer',
        'policeman', 'fireman', 'doctor']
lnames = ['smith', 'brown', 'jones', 'white', 'dawson', 'waller', 'gray',
          'king', 'wallace', 'terry', 'bibby']


class Person(object):
    def __init__(self, age, job, sex, fname, lname):

        self.age = age
        self.job = job
        self.sex = sex
        self.fname = fname
        self.lname = lname

    def __repr__(self):
        string = 'Person(age: {0}, job: {1}, sex: {2}, fname{3}, lname: {4})'
        return string.format(self.age, self.job, self.sex, self.fname,
                             self.lname)

print "Spawning population. Please wait."
person = []
for index in xrange(1, 101):

    cage = random.randint(1, 90)
    cjob = choice(jobs)
    csex = choice(sexes)
    cfname = choice(fnames)
    clname = choice(lnames)
    person.append(Person(cage, cjob, csex, cfname, clname))


print 'population: {0}'.format(len(person))

print person[9].age
person[9].age = 22
print person[9].age
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 781
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: object name from a variable.

Postby sheffieldlad » Mon Apr 15, 2013 9:55 pm

Yoriz wrote:I don't think you really want 100 people floating around your namespace


I take it this would be a bad thing for me to do..

Why is that? I'm not doubting that it's bad, I just don't know why :)

Many thanks for your help Yoriz, I think I'll leave them in a dictionary and iterate over them as you suggested.

-Paul.
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK

Re: object name from a variable.

Postby setrofim » Tue Apr 16, 2013 5:46 am

sheffieldlad wrote:
Yoriz wrote:I don't think you really want 100 people floating around your namespace


I take it this would be a bad thing for me to do..

Why is that?

  1. It pollutes the namespace. Suddenly you have a lot of variables to deal with. Say you want to examine the namespace to see if specific value are there (e.g. while debugging), now you'll get a massive dict scrolling off the edge of your terminal.
  2. It is harder to work with. How do you know there are 100 and not 140, or that they're all there? To determine that you'll have to keep examining the namespace (which, in Python, amounts to manipulating a dict anyway).
  3. Conceptually, those variables are a part of a "collection", so they should actually be a part of a collection. Say you want to do something to all of them (e.g. print them out or write them to a file). Now you have to pass 100 arguments to your output function (or else, *shudder*, have 100 globals). What if you want to add 101st person? Now you have to modify it in a bunch of places; and make sure you modify it in *all* the places -- otherwise you won't get an error, but your code will be subtly wrong (e.g. your output file won't contain the 101st person).

If all your elements are in a collection, you can pass them around as a single variable, you can iterate over all of them (without caring exactly how may there are), you can easily check if an element is already present, etc.

Also, a note about object "names". Variables are external to the objects they refer to. So here
Code: Select all
class Person():
    pass

person1 = Person()

You do not have a Person object called "person1". You have a variable called "person1" that is referring (at this point in the code) to a nameless Person object. If you want your persons to have meaningful names, you should store the name as an attribute of the object itself. If you don't need meaningful names but just need an identifier unique to the person, then all Python objects already have an id which you can access with the built-in id() function (though you almost never need to do that).
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: object name from a variable.

Postby sheffieldlad » Tue Apr 16, 2013 8:37 am

Many thanks setrofim, That's made things a lot clearer in my mind.

-Paul
Python 2.7
Windows XP
sheffieldlad
 
Posts: 37
Joined: Sat Feb 09, 2013 3:03 pm
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider] and 3 guests

cron