我该如何保存比尔·盖茨并在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']
答案 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']