如何将类对象作为参数传递给不同的类方法?
Posted
技术标签:
【中文标题】如何将类对象作为参数传递给不同的类方法?【英文标题】:How can I pass a class object as an argument into a different class method? 【发布时间】:2022-01-10 16:24:14 【问题描述】:我有两门课:
以列表形式保存学生的教室。 和学生
每次我更新学生的分数时,我都想为他/她所在的教室调用 calculate_average。由于明显的原因,下面的代码不起作用,因为我不知道如何为学生所在的教室提供一个函数参数。
class Clas-s-room:
students = None
def __init__(self):
self.students = []
def addStudent(self, student):
self.students.append(student)
def calculate_average(self):
# sums student scores and divides them with student number
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def getInfo(self):
return self.name, self.score
def setScore(self, score):
self.score = score
Clas-s-room.calculate_average()
我怎样才能做到这一点?
【问题讨论】:
【参考方案1】:假设几个学生共享同一个 ClassRoom,您可能想要创建一个命名的 Clas-s-room 实例,然后在实例化它时将其传递给 Student 类。比如:
class Clas-s-room():
def __init__(self):
self.students = []
def addStudent(self, student):
self.students.append(student)
def calculate_average(self):
return sum(x.score for x in self.students if hasattr(x, 'score')) / len(self.students)
class Student():
def __init__(self, clas-s-room):
self.clas-s-room = clas-s-room
self.clas-s-room.addStudent(self)
def setScore(self, score):
self.score = score
clas-s-room1 = Clas-s-room()
student1 = Student(clas-s-room1)
student2 = Student(clas-s-room1)
student1.setScore(100)
student2.setScore(50)
print(clas-s-room1.calculate_average())
# 75
【讨论】:
【参考方案2】:class Clas-s-room:
def __init__(self):
self.students = []
@property
def average(self):
return sum(student.score for student in self.students)/len(self.students)
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f"Student(name=self.name, score=self.score)"
student_1 = Student("John Doe", 10)
student_2 = Student("Jane Doe", 20)
clasroom_1 = Clasroom()
clasroom_1.students.append(student_1)
clasroom_1.students.append(student_2)
clasroom_1.average # 15
student_1.score = 30
clasroom_1.average # 25
使用 python 提供给你的东西。 property
, property(f).setter
, __repr__
.
请务必遵循 pep8 并使用 snake_case 而不是 camelCase
【讨论】:
以上是关于如何将类对象作为参数传递给不同的类方法?的主要内容,如果未能解决你的问题,请参考以下文章