【问题标题】:Is 'self' keyword Mandatory inside the class Methods?类方法中的'self'关键字是强制性的吗?
【发布时间】:2019-10-17 07:02:22
【问题描述】:

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

【问题讨论】:

标签: python class object self


【解决方案1】:

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

get_biggest_number 方法中,您只需循环遍历将包含 Student 实例的 Student.instances 列表,您可以访问 instance.age 实例变量:

@staticmethod
def get_biggest_number():
  for student_instance in Student.instances:
    student_instance.age  # will give you age of the instance

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您不应该将类方法与实例方法混淆。 在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')
    

    【讨论】:

      【解决方案3】:

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

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

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

      输出将是43

      【讨论】:

        【解决方案4】:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多