如何用用户定义的类实例填充Python列表?

0 投票
2 回答
3910 浏览
提问于 2025-04-16 17:43

我想用我自己定义的一个类的实例来填充一个列表,但每次我尝试访问列表中的任何元素时都会出错。下面是我的代码。

如果能帮我解决这个问题,我会非常感激!

class Population:
"""total population of workers"""
    workerl = []

    def __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 = []
        for i in range(workers):
            print i #test
            x = Worker()
            workerl.append(x)

p = 0
workers = 0

def showUR():
    """displays number of unemployed workers in a population"""
    ur = 0
    for worker in workers:
        if worker.isemployed == true:
            ur = ur + 1
    print ur

def advance(time, p):
    """advances one unit of time"""



# population as an array of workers     
class Worker:
    """a worker in a population"""
    isemployed = True

x = Population(.2, 100) 
print x.p
print x.workerl
if x.workerl[0].isemployed:
    print "worker 1 is employed"

2 个回答

0

你创建了一个函数内部的变量 workerl,把它填充好了,但忘记了它的存在。

记住,在Python中,你总是需要写 self.(或者你用的实例参数)来访问类里的成员。此外,你也可以通过实例来读取类的成员,所以 self.workerlx.workerl 都能获取到这个变量的值。但是,如果你想要设置这个变量的值,就必须用 Population.workerl =,因为如果你写 self.workerl =,那样会把它在当前实例中覆盖掉。

2

你的程序在很多方面都有问题。

class Population:
"""total population of workers""" # <-- indentation error
    workerl = [] # <-- class attribute, never used

    def __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.workerl
        for i in range(workers):
            print i #test
            x = Worker()
            workerl.append(x)

p = 0 # <-- module variable, never used
workers = 0 # <-- module variable, never used

def showUR(): # <-- 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 = 0
    for worker in workers: # should be self.workerl, not workers
        if worker.isemployed == true: # <-- typo, should be: True
            ur = ur + 1
    print ur

def advance(time, p):
    """advances one unit of time"""



# population as an array of workers # <-- Python lists are not arrays
class Worker:
    """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"

这可能是你程序应该长得样子(没有注释的部分):

class Worker(object):

    def __init__(self):
        self.is_employed = True


class Population(object):

    def __init__(self, probability, number_of_workers):
        self.probability = probability
        self.workers = [Worker() for each in range(number_of_workers)]

    def showUR(self):
        print sum(not worker.is_employed for worker in self.workers)


x = Population(.2, 100)
print x.probability
print len(x.workers)
print x.workers
if x.workers[0].is_employed:
    print "worker 1 is employed"

撰写回答