The Artima Developer Community
Sponsored Link

Python Answers Forum
assign values to members of class objects

1 reply on 1 page. Most recent reply: Nov 6, 2007 9:26 AM by justin quick

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
john liu

Posts: 1
Nickname: jliu
Registered: Nov, 2007

assign values to members of class objects Posted: Nov 5, 2007 11:59 AM
Reply to this message Reply
Advertisement
Hi,

I have a question regard to assign the values to each memebrs of the class objects because I have a large list of class objects. Can I do the following? If not, how can I achieve the same thing? Thanks in advance.

class person():
def __init__(self):
self.name = ' '
self.job = ' '
self.age = 0

# define a list of class objects
personList = []

personList[0].name = 'abc'
personList[0].job = 'worker'
personList[0].age = 20
personList[1].name = 'efg'
personList[1].job = 'student'
personList[1].age = 22
personList[2].name = 'hlk'
personList[2].job = 'doctor'
personList[2].age = 25


justin quick

Posts: 3
Nickname: justquick
Registered: Nov, 2007

Re: assign values to members of class objects Posted: Nov 6, 2007 9:26 AM
Reply to this message Reply
This should work, just not very efficiently, so use either this

person1 = personList[0]
person1.name = 'abc'
person1.job = 'worker'
person1.age = 20

Or iteratively

for person in personList:
person.name = 'abc'
person.job = 'worker'
person.age = 20

You can also set these variables in the class's __init__ method by rearranging the class like so

class person():
def __init__(self,name='',job='',age=0):
self.name = name
self.job = job
self.age = age
person1 = person('abc','worker',20)

Flat View: This topic has 1 reply on 1 page
Topic: windows service - get current logged on user Previous Topic   Next Topic Topic: search patterns and parse data into dict

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use