如何在 class 中使用不同的多用户输入在字典中添加数据?
How to add data on a dictionary using different multiple user input inside a class?
我有一个简单的程序,它使用用户输入获取用户 name
和 age
。如果另一个用户输入新的姓名和年龄,我如何将数据存储在字典中并更新数据。这是我的示例代码。不知道我做的对不对。
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
class 的每个实例都是一个有名字和年龄的人。现在我不知道你是否假设一名员工可以有多个名字(这就是为什么你需要一本字典)或者你只需要一个对象来收集每个用户的信息。
如果你想维护class里面的input
,把它移到构造函数里,也就是__init__
方法。
我会使用另一个对象,例如 list
来收集用户集。
我还在 class 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()
我有一个简单的程序,它使用用户输入获取用户 name
和 age
。如果另一个用户输入新的姓名和年龄,我如何将数据存储在字典中并更新数据。这是我的示例代码。不知道我做的对不对。
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
class 的每个实例都是一个有名字和年龄的人。现在我不知道你是否假设一名员工可以有多个名字(这就是为什么你需要一本字典)或者你只需要一个对象来收集每个用户的信息。
如果你想维护class里面的input
,把它移到构造函数里,也就是__init__
方法。
我会使用另一个对象,例如 list
来收集用户集。
我还在 class 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()