如何在l中同时保留名字和姓氏?

时间:2019-06-22 16:10:08

标签: python python-3.x

我该如何保存比尔·盖茨并在lis上标记扎克伯格?

当我写到sedond时,第一个丢失了

class student:
    def __init__(self,name,surname):
        self.name=name
        self.surname=surname
    def studen(self):
        lis=[]
        lis.extend([self.name,self.surname])
        return lis

a=student("Bill","gates")
a=student("Mark","zuckerberg")
print(a.studen())

结果:

['Mark', 'zuckerberg']

我要

['Mark', 'zuckerberg', 'bill', 'gates']

2 个答案:

答案 0 :(得分:1)

您可能需要一个class Student和一个class Students来代表Student的集合:

也许是这样的:

class Student:

    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

    def __str__(self):
        return f'{self.name}, {self.surname}'

    def __repr__(self):
        return str(self)


class Students:

    def __init__(self, seq):
        self._students = seq[:]

    def append(self, student):
        self._students.append(student)

    def __str__(self):
        return '\n'.join(str(student) for student in self._students)


if __name__ == '__main__':

    bill = Student("Bill", "Gates")
    mark = Student("Mark", "Zuckerberg")
    students = Students([mark, bill])
    print(students)

输出:

Mark, Zuckerberg
Bill, Gates

您还可以从list模块继承collections或某些基类;更简单地说,您还可以使用简单的python列表来保存Student的实例:

class Student:

    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

    def __str__(self):
        return f'{self.name} {self.surname}'

    def __repr__(self):
        return str(self)


if __name__ == '__main__':

    bill = Student("Bill", "Gates")
    mark = Student("Mark", "Zuckerberg")
    students = [mark, bill]
    print(students)

输出:

[Mark Zuckerberg, Bill Gates]

答案 1 :(得分:1)

使lis为实例属性。您这样做会覆盖实例a,因此先前的值会丢失。

您可以这样做:

class student:
    def __init__(self,name,surname):
        self.name = name
        self.surname = surname
        self.lis = [self.name, self.surname]
    def studen(self):
        return self.lis

a = student("Bill", "gates")
b = student("Mark", "zuckerberg")
print(a.studen() + b.studen())
# ['Bill', 'gates', 'Mark', 'zuckerberg']