“self”关键字在类方法中是必需的吗?

2024-03-18

我是 python 初学者,我了解到该方法中的第一个参数应该包含一些“self”关键字,但我发现以下程序在没有 self 关键字的情况下运行,你能解释一下吗,下面是我的代码...

class Student(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def get_biggest_number(*age):
        result=0
        for item in age:
            if item > result:
                result= item
        return result


Sam = Student("Sam",18)
Peter = Student("Peter",20)
Karen = Student("Karen",22)
Mike = Student("Michael",21)

oldest= Student.get_biggest_number(Sam.age,Peter.age,Karen.age,Mike.age)
print (f"The oldest student is {oldest} years old.")

您发布的代码中存在缩进错误,您应该首先缩进方法及其内容,这意味着方法位于类内。另一方面,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

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“self”关键字在类方法中是必需的吗? 的相关文章

随机推荐