How Do I Fill A List In Python With User-defined Class Instances?
So I'm trying to fill a list with instances of a class that I defined myself, but I keep getting an error when I try to access any element in the list. The code is below. Any help
Solution 1:
Your program is flawed on oh so many levels.
classPopulation:
"""total population of workers"""# <-- indentation error
workerl = [] # <-- class attribute, never useddef__init__(self, p, workers):
# probability of a worker becoming unemployed# low in booms, high in recessions, could be a proxy for i
self.p = p
self.workers = workers
workerl = [] # <-- local variable, should be self.workerlfor i inrange(workers):
print i #test
x = Worker()
workerl.append(x)
p = 0# <-- module variable, never used
workers = 0# <-- module variable, never useddefshowUR(): # <-- should be a method of population"""displays number of unemployed workers in a population"""# <-- does the opposite, i.e., shows the number of EMPLOYED workers
ur = 0for worker in workers: # should be self.workerl, not workersif worker.isemployed == true: # <-- typo, should be: True
ur = ur + 1print ur
defadvance(time, p):
"""advances one unit of time"""# population as an array of workers # <-- Python lists are not arraysclassWorker:
"""a worker in a population"""
isemployed = True# <-- class atrribute, when set to False ALL workers become unemployed at once
x = Population(.2, 100)
print x.p
print x.workerl
if x.workerl[0].isemployed:
print"worker 1 is employed"
And this is how your program should probably look like (sans comments):
classWorker(object):
def__init__(self):
self.is_employed = TrueclassPopulation(object):
def__init__(self, probability, number_of_workers):
self.probability = probability
self.workers = [Worker() for each inrange(number_of_workers)]
defshowUR(self):
printsum(not worker.is_employed for worker in self.workers)
x = Population(.2, 100)
print x.probability
printlen(x.workers)
print x.workers
if x.workers[0].is_employed:
print"worker 1 is employed"
Solution 2:
You created function-local variable workerl
, correctly filled it in and forgot it.
Remember, that you always have to write self.
(or whatever your instance parameter was) to access members in python. Also you can read class member via instance, so self.workerl
/x.workerl
will evaluate to it, but to set it you have to call Population.workerl =
, because self.workerl =
would override it in the instance.
Post a Comment for "How Do I Fill A List In Python With User-defined Class Instances?"