首页 > 解决方案 > 人员类重复相同的输入

问题描述

我正在尝试创建一个名为“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()

标签: pythonpython-3.xclass

解决方案


除了以上评论:

为了提升 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

推荐阅读