2011-05-16 2 views
0

그래서 내가 정의한 클래스의 인스턴스로 목록을 채우려하고 있지만 목록의 요소에 액세스하려고하면 오류가 계속 발생합니다. 코드는 다음과 같습니다.사용자 정의 클래스 인스턴스로 파이썬 목록 작성 방법은 무엇입니까?

도움이 될 것입니다.

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" 
+1

두 팁 : 코드를 포맷은 구문 적으로 유효한 파이썬 (들여 쓰기, 등)의 있도록하고 정확한 게시 오류가 발생했습니다 (코드로도 포맷 됨). – detly

+1

아아, 나는 네가 들여 쓰기가 힘들다는 것을 깨달았다. 거기에 몇 가지 탭이 있기 때문이다. 코드를 편집하여 공백으로 변환하십시오. – detly

답변

0

함수 로컬 변수 workerl을 올바르게 작성하고 잊어 버렸습니다.

파이썬의 멤버에 액세스하려면 항상 self. (또는 인스턴스 매개 변수가 무엇이든)을 써야한다는 것을 기억하십시오. 또한 인스턴스를 통해 클래스 멤버를 읽을 수 있으므로 self.workerl/x.workerl으로 평가되지만 self.workerl =은 인스턴스에서이 인스턴스를 재정의하므로 Population.workerl =을 호출해야합니다.

+0

Perfect, that fixed! 감사합니다 1 월. –

1

프로그램에 많은 결함이 있습니다.

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" 
관련 문제