类方法中的'self'关键字是强制性的吗?

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


慕婉清6462132
浏览 119回答 4
4回答

FFIVE

您发布的代码中有缩进错误,您应该首先缩进方法及其内容,这意味着方法在类中。另一方面,self引用实例,它调用特定的方法并提供对所有实例数据的访问。例如student1 = Student('name1', 20)student2 = Student('name2', 21)student1.some_method(arg1)在最后一次调用中,在后台student1传递了方法的 self 参数,这意味着所有 student1 的数据都可以通过self参数获得。您正在尝试使用,它没有实例的数据,旨在在没有显式实例的情况下对类相关函数进行逻辑分组,这在方法定义staticmethod中不需要:selfclass 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在get_biggest_number方法中,您只需遍历Student.instances包含 Student 实例的列表,您就可以访问instance.age实例变量:@staticmethoddef get_biggest_number():  for student_instance in Student.instances:    student_instance.age  # will give you age of the instance希望这可以帮助。

叮当猫咪

您不应该将 classmethod 与实例方法混淆。在python中,您可以将类中的方法声明为classmethod。此方法将类的引用作为第一个参数。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')

缥缈止盈

self在 python 中是指创建的类的实例。类似于thisC# 和 Java 中的东西。但是有一些区别,但简而言之:当您不用self作方法的输入时,实际上您是在说此方法不需要任何实例,这意味着此方法是一个static method并且永远不会使用任何类属性。在您的示例中,我们get_biggest_number甚至可以调用没有一个实例的方法,例如,您可以像这样调用此方法:Student.get_biggest_number(20,30,43,32)输出将是43.

jeck猫

self 关键字用于表示给定类的实例(对象)。...但是,由于类只是一个蓝图,因此 self 允许访问 python 中每个对象的属性和方法。class ClassA:    def methodA(self, arg1, arg2):        self.arg1 = arg1        self.arg2 = arg2假设 ObjectA 是该类的一个实例。现在,当调用 ObjectA.methodA(arg1, arg2) 时,python 在内部将其转换为:ClassA.methodA(ObjectA, arg1, arg2)self 变量引用对象本身,代码变为:class ClassA:    def methodA(ObjectA, arg1, arg2):        ObjectA.arg1 = arg1        ObjectA.arg2 = arg2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python