2016-09-26 3 views
1

도시에 대한 채우기 파일에 채우기 파일이 누락되었지만이 메시지가 표시 될 때 아래 오류 코드에 오류 처리를 통합하고자합니다.사전에 누락 된 값에 대한 오류 처리

형식 오류 : 기술자 'GET'는 '딕셔너리'객체를 필요로하지만, 'STR'

import csv 
import sys 
import time 


input_file = ('\myInput_file.csv') 
output_file = ('\myOutput_file.csv') 
population_file = ('\myPopulation_file.csv') 

populations = {} 

with open(population_file, 'r') as popfile: 
    for line in csv.reader(popfile): 
     populations[line[2]] = line[3] 


with open(input_file, 'r') as infile, open(output_file, 'w', newline='') as outfile: 
reader = csv.reader(infile) 
writer = csv.writer(outfile, delimiter = ',') 

for row in reader: 

    population = dict.get(populations[row[0] + row[1]], None) 
    new_line = [row[0]+row[1], population] 
    writer.writerow(new_line) 

답변

0

시도 수신 : get()이있다

population = populations.get(row[0] + row[1], None) 

오류의 원인이된다을 기본 형식 dict의 메서드 설명자 다른 메쏘드들 (클래스의 멤버 인 함수들)과 마찬가지로, 그것들은 연산을 수행하기위한 첫 번째 인자를 객체로 요구한다. 다음 코드를 고려하십시오

class Thing(object): 
    def get(self, something): 
     # ... 

get()는 두 개의 매개 변수, something, 당신이 얻을하려는 것뿐만 아니라 self, 당신에서 그것을 얻을 할 개체를 필요로하는 클래스 Thing의 방법이다.

populations.get() (dict 개체 populations 사용)을 호출하면 개체가 첫 번째 인수로 자동 전달됩니다. 이것은 바운드 메소드의 특징입니다. 'dict.get()'(dict 클래스 dict 사용)을 호출하면 인수로 전달할 dict 객체를 알지 못하므로 명시 적으로 제공해야합니다.

는 다음과 같은 고려 :

>>> Thing.get 
<function Thing.get at 0x103ff6730> 
>>> a = Thing() 
>>> a.get 
<bound method Thing.get of <__main__.Thing object at 0x104002cf8>> 
>>> 

여기가 아닌 내장 클래스에 동일한 오류를 만들 때 발생하는 내용은 다음과 같습니다 자세한 답변

>>> Thing.get('foo') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: get() missing 1 required positional argument: 'something' 
+0

감사합니다! 너는 나에게 슬픔을 많이 덜어 준다. – DJohnson1990

관련 문제