python - 人员类重复相同的输入
问题描述
我正在尝试创建一个名为“Person”的类,只需按用户的名字、姓氏、年龄和国家/地区添加用户,包括自动编号 ID。虽然当我输入详细信息时,所有详细信息都重复显示相同的详细信息,我希望 ID 增加 1,例如用户 1 属于 ID 1,用户 2 属于 ID 2 等。
我希望我的程序如何工作:
------------------------------
ID: 1
FIRST NAME: John
LAST NAME: Smith
AGE: 32
COUNTRY: United Kingdom
------------------------------
------------------------------
ID: 2
FIRST NAME: Amanda
LAST NAME: Smith
AGE: 56
COUNTRY: Germany
------------------------------
我的程序如何显示:
Enter First Name: John
Enter Last Name: Smith
Enter Age: 32
Enter Country: United Kindom
Add another person? Y or N: N
Finished
------------------------------
ID: 1
FIRST NAME: John
LAST NAME: Smith
AGE: 32
COUNTRY: United Kingdom
------------------------------
------------------------------
ID: 1
FIRST NAME: John
LAST NAME: Smith
AGE: 32
COUNTRY: United Kingdom
------------------------------
谁能指出我在这里出错的地方?或如何解决我的问题?
我的 Python 代码:
class Person:
personid = 0
def __init__(self, firstname, lastname, age, country):
self.personid =+ 1
self.firstname = firstname
self.lastname = lastname
self.age = age
self.country = country
def addPerson(self):
person = []
person.append(self.personid)
person.append(self.firstname)
person.append(self.lastname)
person.append(self.age)
person.append(self.country)
def displayPeople(self):
print("-" * 30)
print("PERSON ID: ",self.personid)
print('FIRST NAME:',self.firstname,'\nLAST
NAME:',self.lastname,'\nAGE:',self.age,'\nCOUNTRY:',self.country)
print("-" * 30)
def addAnotherPerson(self):
option = input("Add another person? Y or N: ")
if option == "Y":
Person(
firstname=input("Enter First Name: "),
lastname=input("Enter Last Name: "),
age=input("Enter Age: "),
country=input("Enter Country: ")
)
Person.addAnotherPerson(self)
Person.displayPeople(self)
else:
print("Finished")
Person.displayPeople(self)
perx = Person(
firstname = input("Enter First Name: "),
lastname = input("Enter Last Name: "),
age = input("Enter Age: "),
country = input("Enter Country: ")
)
perx.addPerson()
perx.displayPeople()
perx.addAnotherPerson()
解决方案
除了以上评论:
为了提升 person_id,您需要显式更新类成员而不是实例成员。
这就是你需要的:
class Person:
cls_personid = 0
def __init__(self, firstname, lastname, age, country):
type(self).cls_personid += 1
self.personid = self.cls_personid
self.firstname = firstname
self.lastname = lastname
self.age = age
self.country = country
a = Person('a1','b1', 11, 'xyz')
b = Person('a2','b2', 12, 'xyz')
print(a.personid) # -> 1
print(b.personid) # -> 2
推荐阅读
- extjs - 当我们单击网格列即单击网格列时,自定义日期排序不起作用
- reactjs - 将主题合并到 react-minimal-pie-chart 中不起作用
- django - 未找到 gunicorn 静态文件
- javascript - 为什么我的 3D 模型没有使用 glTF 加载器在 three.js 中加载?
- xsl-fo - XSL-FO 到 PDF 的翻译产生了意想不到的结果
- angular - 在 Angular 2 应用程序中存储和跟踪私人聊天消息的最佳方式
- c# - 使用 Skype 机器人进行音频通话
- python - 数字取反
- javascript - 在第一次请求失败后,我如何设法提出不同的请求
- dictionary - TomTom 地图:如何使用自定义搜索栏搜索位置?