클래스 내에서 다른 여러 사용자 입력을 사용하여 사전에 데이터를 추가하는 방법은 무엇입니까?

감자 군

사용자 nameage사용자 입력을 사용 하는 간단한 프로그램이 있습니다. 다른 사용자가 새 이름과 나이를 입력하면 데이터를 사전에 저장하고 데이터를 업데이트하려면 어떻게해야합니까? 다음은 내 샘플 코드입니다. 내가 제대로하고 있는지 모르겠다.

class Name:
    data = {}
    num_employee = 0

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Name.num_employee += 1

    @classmethod
    def user_in(cls):
        name = input('Enter name: ')
        age = int(input('Enter age: '))
        return cls(name, age)

    def show(self):
        Name.data = {'name': self.name, 'age': self.age}
        return Name.data


employ = Name.user_in()
employ2 = Name.user_in()
print(Name.num_employee)
print(employ.show())

Name클래스 의 모든 인스턴스는 이름과 나이를 가진 사람입니다. 이제 직원이 둘 이상의 이름을 가질 수 있다고 가정하거나 (그리고 이것이 사전이 필요한 이유) 모든 사용자에 대한 정보를 수집하기 위해 단순히 객체가 필요한지 알 수 없습니다.

당신이 mantain하려는 경우 input클래스의 내부는 생성자로 이동 __init__하는 방법. 같은 다른 개체를 사용 list하여 사용자 집합을 수집합니다.

또한 Person사용자가 새로운 입력으로 나이와 이름을 수정할 수 있도록 클래스에 두 가지 메서드를 추가했습니다 .

class Person:
    def __init__(self):
        self.name = input('Enter name: ')
        self.age = int(input('Enter age: '))

    def show(self):
        data = {'name': self.name, 'age': self.age}
        return data

    def change_name(self):
        self.name = input('Update name: ')

    def change_age(self):
        self.age = int(input('Update age: '))

persons = []

employ = Person()
employ2 = Person()

# add employ to the list
persons.append(employ)
persons.append(employ2)

# to show information
print(len(persons)) # len of the list is the number of employees
print(employ.show())

# to change employ1 name you can do
employ.change_name()

# to change employ2 age do
employ2.change_age()

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관