Reputation: 93
How can I save bill gates and mark zuckerberg in lis?
When I write to the sedond, the first is lost
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())
result:
['Mark', 'zuckerberg']
i want:
['Mark', 'zuckerberg', 'bill', 'gates']
Upvotes: 1
Views: 54
Reputation: 36702
You probably need a class Student
, and a class Students
to represent a collection of Student
:
Maybe something like this:
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
You could also subclass list
, or some base class from the collections
module; More simply, you also could use a plain python list to hold your instances of 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]
Upvotes: 1
Reputation: 26039
Make lis
an instance attribute. The way you do overrides instance a
, so the previous value is lost.
You can do:
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']
Upvotes: 1