“自"关键字是否在“方法"类中是必需的? [英] Is 'self' keyword Mandatory inside the class Methods?
问题描述
我是python Begineer,我了解到该方法中的第一个参数应该包含一些'self'关键字,但是我发现以下程序在没有self关键字的情况下运行,您可以在下面解释一下这是我的代码...
I am python Begineer and i learned that first parameter inside the method should be contain some 'self' keyword but i found the following program runs without self keyword can you explain about this below is my code...
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
引用实例,该实例调用特定的方法并提供对所有实例数据的访问权限.例如
Code you've posted has indentation errors within it, you should first indent methods and it's content, meaning that, methods are within class. On the other hand, self
refers to instance, which calls specific method and gives access to the all instance data. For example
student1 = Student('name1', 20)
student2 = Student('name2', 21)
student1.some_method(arg1)
在最后一次调用中,
在后台为该方法的self参数传递了 student1
,这意味着可以通过 self
参数获得所有student1的数据.
in the last call, behind the scenes student1
is passed for self parameter of the method, meaning that all student1's data is available through self
argument.
您要使用的是 staticmethod
,该方法没有实例数据,并且旨在在没有显式实例的情况下对与类相关的函数进行逻辑分组,而无需显式实例>在方法定义中:
What you are trying is to use staticmethod
, which has no data of the instance and is aimed to logically group class related functions without explicit instance, which does not require self
in method definition:
class Student:
...
@staticmethod
def get_biggest_number(*ages):
# do the task here
另一方面,如果您想跟踪所有学生实例并应用get_biggest_number方法自动对其进行处理,则只需定义类变量(而不是实例变量),并在每个实例上定义 __ init __
将新实例附加到该列表:
On the other hand, if you would like to track all student instances and apply get_biggest_number method automatically work on them, you just have to define class variable (rather than instance variable) and on each instance __init__
append new instance to that list:
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
实例变量:
and in get_biggest_number
method you just loop through Student.instances
list which will contain Student instance and you can access instance.age
instance variable:
@staticmethod
def get_biggest_number():
for student_instance in Student.instances:
student_instance.age # will give you age of the instance
希望这会有所帮助.
这篇关于“自"关键字是否在“方法"类中是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!