人员类重复相同的输入

时间:2019-11-08 19:54:59

标签: python python-3.x class

我正在尝试创建一个名为“ Person”的类,只需按用户的名字,姓氏,年龄和国家(包括自动编号ID)添加用户即可。尽管当我输入详细信息时,所有详细信息都重复显示相同的详细信息,而我希望ID像用户1一样增加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()

1 个答案:

答案 0 :(得分:0)

除了以上注释:

为了提升person_id,您要显式更新 class 成员而不是实例成员。

这就是您需要的:

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