2017-11-29 8 views
-1
여기

내 프로그램입니다 :루프에서 만든 객체가 왜 같은 이유입니까?

일부 클래스 :

내가 JSON에서 일부 데이터를 읽으려고보다
class Employee (object): 

    @classmethod 
    def __init__(self, id, name, password): 
     self.id = id 
     self.name = name 
     self.password = password 

    @classmethod 
    def toString(self): 
     return(self.id + ": " + self.name + " " + self.password) 

: 어떤 문제가 아니라 언제없이 데이터를 읽을 수

import os 
import json 

if os.name == 'nt': 
    path = r'Storage\employee.json' 
else: 
    path = r'Storage/employee.json' 

from employee import Employee 

if __name__ == '__main__': 
    with open(path, 'r') as file: 
     json_list = json.loads(file.read()) 
     list = [Employee(item['id'], item['name'], item['password']) for item in json_list] 
     for elemt in list: 
      print (elemt.toString()) 

I 그것을 가진 종업원의 명부를 만드는 것을 시도하십시오. 목록은 마지막 객체의 반복이됩니다.

+3

정지 : 오히려, 당신은 파이썬 __repr__ 방법을 사용할 수 있습니다. 그것은 당신이 생각하는 것을 의미하지는 않습니다. – user2357112

+1

'__init__'은 ** 아닙니다 ** @ classmethod'이며'toString' (이것은 클래스 메쏘 잘가 아닙니다)은 아마도'__str__'을 의미 할 것입니다 – alfasin

+0

이 경우 둘 다'toString()'이 아닙니다. –

답변

1

@classmethod으로 메서드에 주석을다는 것은 특정 인스턴스가 아닌 클래스에 속함을 의미합니다. Employee 클래스의 두 메소드에서 해당 데코레이터를 제거하면 OK입니다.

1

classmethod이 경우에는 생각대로 작동하지 않습니다. 모든 메소드에`classmethod` 퍼팅

class Employee: 
    def __init__(self, *args): 
     self.__dict__ = dict(zip(['id', 'name', 'password'], args)) 
    def __repr__(self): 
     return "{id}:{name} {password}".format(**self.__dict__) 

list = [Employee(item['id'], item['name'], item['password']) for item in json_list]