您发布的代码中存在缩进错误,您应该首先缩进方法及其内容,这意味着方法位于类内。另一方面,self
指实例,它调用特定方法并提供对所有实例数据的访问。例如
student1 = Student('name1', 20)
student2 = Student('name2', 21)
student1.some_method(arg1)
在最后一次通话中,在幕后student1
作为方法的 self 参数传递,这意味着所有 Student1 的数据都可以通过self
争论。
你正在尝试的是使用staticmethod
,它没有实例的数据,旨在在没有显式实例的情况下对类相关函数进行逻辑分组,这不需要self
在方法定义中:
class Student:
...
@staticmethod
def get_biggest_number(*ages):
# do the task here
另一方面,如果您想跟踪所有学生实例并自动应用 get_biggest_number 方法,您只需定义类变量(而不是实例变量)并在每个实例上__init__
将新实例附加到该列表中:
class Student:
instances = list() # class variable
def __init__(self, name, age):
# do the task
Student.instances.append(self) # in this case self is the newly created instance
and in get_biggest_number
你刚刚循环的方法Student.instances
列表将包含 Student 实例,您可以访问instance.age
实例变量:
@staticmethod
def get_biggest_number():
for student_instance in Student.instances:
student_instance.age # will give you age of the instance
希望这可以帮助。