'self' 关键字是否在 class 方法中是必需的?

Is 'self' keyword Mandatory inside the class Methods?

我是 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.")

您发布的代码中有缩进错误,您应该首先缩进方法及其内容,这意味着方法在 class 内。另一方面,self 指的是实例,它调用特定的方法并提供对所有实例数据的访问。例如

student1 = Student('name1', 20)
student2 = Student('name2', 21)
student1.some_method(arg1)

在最后一次调用中,在幕后为方法的 self 参数传递了 student1,这意味着所有 student1 的数据都可以通过 self 参数获得。

你正在尝试的是使用 staticmethod,它没有实例数据,目的是在逻辑上对 class 相关函数进行分组,而不需要显式实例,这不需要 self 在方法定义中:

class Student:
  ...
  @staticmethod
  def get_biggest_number(*ages):
    # do the task here

另一方面,如果您想跟踪所有学生实例并应用 get_biggest_number 方法自动处理它们,您只需定义 class 变量(而不是实例变量)和在每个实例上 __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

并且在 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

希望这对您有所帮助。

您不应将 class方法与实例方法混淆。 在 python 中,您可以将 class 中的方法声明为 class 方法。 此方法将对 class 的引用作为第一个参数。

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

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

    @classmethod
    def get_classname(cls):
        # Has only access to class bound items
        # gets the class as argument to access the class
        return cls.__name__

    @staticmethod
    def print_foo():
        # has not a reference to class or instance
        print('foo')
python中的

self指的是创建的class的实例。类似于 C# 中的 this 和 Java。但是有一些区别,但简而言之:当你不使用 self 作为方法的输入时,实际上你是在说这个方法不需要任何实例,这意味着这个方法是 static method并且永远不会使用任何 class 属性。

在您的示例中,我们甚至可以在没有一个实例的情况下调用 get_biggest_number 方法,例如,您可以像这样调用此方法:

Student.get_biggest_number(20,30,43,32)

并且输出将是 43

self 关键字用于表示给定class 的实例(对象)。 ... 但是,由于 class 只是一个蓝图,self 允许访问 python.

中每个对象的属性和方法
class ClassA:

    def methodA(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

假设 ObjectA 是 class.

的一个实例

现在当调用 ObjectA.methodA(arg1, arg2) 时,python 在内部将其转换为:

ClassA.methodA(ObjectA, arg1, arg2)

self变量指的是对象本身,代码变为:

class ClassA:

    def methodA(ObjectA, arg1, arg2):
        ObjectA.arg1 = arg1
        ObjectA.arg2 = arg2