“自我”一词的目的是什么?

问题:“自我”一词的目的是什么?

selfPython 中的单词的目的是什么?我知道它是指从该类创建的特定对象,但是我看不到为什么要将它显式地作为参数添加到每个函数中。为了说明这一点,在Ruby中,我可以这样做:

class myClass
    def myFunc(name)
        @name = name
    end
end

我很容易理解。但是在Python中,我需要包括self

class myClass:
    def myFunc(self, name):
        self.name = name

有人可以通过这个告诉我吗?我的经历(公认有限)并不是我遇到的。

What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can’t see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:

class myClass
    def myFunc(name)
        @name = name
    end
end

Which I understand, quite easily. However in Python I need to include self:

class myClass:
    def myFunc(self, name):
        self.name = name

Can anyone talk me through this? It is not something I’ve come across in my (admittedly limited) experience.


回答 0

需要使用的原因self.是因为Python不使用@语法来引用实例属性。Python决定以一种使该方法所属的实例自动传递但不会自动接收的方式进行方法:方法的第一个参数是调用该方法的实例。这使方法与函数完全相同,并保留实际名称供您使用(尽管self是约定俗成的,当您使用其他方法时,人们通常会皱着眉头。)self对于代码而言并不特殊,它只是另一个对象。

Python可以做一些其他事情来区分普通名称和属性-像Ruby这样的特殊语法,或者像C ++和Java这样的声明都需要,或者也许还有其他不同-但事实并非如此。Python的全部目的是使事情变得明确,使事情变得显而易见,尽管它并非在所有地方都做到这一点,但它确实为实例属性做到了。因此,分配给实例属性需要知道要分配给哪个实例,这就是为什么需要的原因self.

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it’s just another object.

Python could have done something else to distinguish normal names from attributes — special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different — but it didn’t. Python’s all for making things explicit, making it obvious what’s what, and although it doesn’t do it entirely everywhere, it does do it for instance attributes. That’s why assigning to an instance attribute needs to know what instance to assign to, and that’s why it needs self..


回答 1

让我们看一个简单的向量类:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

我们希望有一种计算长度的方法。如果我们想在类中定义它,它将是什么样?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

当我们将其定义为全局方法/函数时,它应该是什么样?

def length_global(vector):
    return math.sqrt(vector.x ** 2 + vector.y ** 2)

因此,整个结构保持不变。我该如何利用呢?如果我们暂时假设没有lengthVector类编写方法,则可以执行以下操作:

Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0

之所以有效,是因为的第一个参数length_global可以用作中的self参数length_new。没有明确的说法,这是不可能的self


理解显式需求的另一种方法self是查看Python在何处添加了一些语法糖。当您牢记时,基本上,

v_instance.length()

在内部转换为

Vector.length(v_instance)

很容易看到self适合的位置。您实际上并没有用Python编写实例方法;您编写的是必须将实例作为第一个参数的类方法。因此,您必须将实例参数显式放置在某处。

Let’s take a simple vector class:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

What should it look like when we were to define it as a global method/function?

def length_global(vector):
    return math.sqrt(vector.x ** 2 + vector.y ** 2)

So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length method for our Vector class, we could do this:

Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0

This works because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self.


Another way of understanding the need for the explicit self is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like

v_instance.length()

is internally transformed to

Vector.length(v_instance)

it is easy to see where the self fits in. You don’t actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.


回答 2

假设您有一个ClassA包含methodA定义为以下方法的类:

def methodA(self, arg1, arg2):
    # do something

并且ObjectA是此类的一个实例。

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

ClassA.methodA(ObjectA, arg1, arg2)

self变量是指对象本身。

Let’s say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.


回答 3

实例化对象时,对象本身将传递到self参数中。

因此,对象的数据绑定到该对象。下面是一个示例,您可以如何可视化每个对象的数据外观。注意如何用对象名称替换“自我”。我并不是说下面的示例图是完全准确的,但希望它可以用于可视化自我的使用。

将对象传递到self参数中,以便对象可以保留其自己的数据。

尽管这可能并不完全准确,但是请考虑如下实例化对象的过程:制作对象时,它将类用作其自己的数据和方法的模板。如果不将其自身的名称传递给self参数,则该类中的属性和方法将保留为常规模板,并且不会引用该对象(属于该对象)。因此,通过将对象的名称传递给self参数,这意味着,如果从一个类实例化100个对象,则它们都可以跟踪自己的数据和方法。

请参见下图:

When objects are instantiated, the object itself is passed into the self parameter.

Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I’m not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it’s own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object’s name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.

See the illustration below:


回答 4

我喜欢这个例子:

class A: 
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]

class A: 
    def __init__(self): 
        self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: []

I like this example:

class A: 
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]

class A: 
    def __init__(self): 
        self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: []

回答 5

我将用不使用类的代码进行演示:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

类只是避免始终传递此“状态”事物的一种方法(以及其他诸如初始化,类组合,很少需要的元类以及支持自定义方法以覆盖运算符之类的美好事物)的方法。

现在,让我们使用内置的python类机制来演示上面的代码,以显示其基本相同之处。

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[从重复的封闭式问题中迁移了我的答案]

I will demonstrate with code that does not use classes:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

Classes are just a way to avoid passing in this “state” thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).

Now let’s demonstrate the above code using the built-in python class machinery, to show how it’s basically the same thing.

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[migrated my answer from duplicate closed question]


回答 6

以下摘录来自Python文档中关于self的内容

与Modula-3中一样,[Python]中没有用于从其方法引用该对象的成员的简写:方法函数以表示该对象的显式第一个参数声明,该参数由调用隐式提供。

通常,方法的第一个参数称为self。这无非是一种约定:self对Python绝对没有特殊的含义。但是请注意,如果不遵循该约定,则其他Python程序员可能对代码的可读性较低,并且还可以想到可能会依赖此类约定编写类浏览器程序。

有关更多信息,请参见关于类Python文档教程

The following excerpts are from the Python documentation about self:

As in Modula-3, there are no shorthands [in Python] for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

For more information, see the Python documentation tutorial on classes.


回答 7

除已说明的所有其他原因外,它还允许更轻松地访问重写的方法;你可以打电话Class.some_method(inst)

一个有用的例子:

class C1(object):
    def __init__(self):
         print "C1 init"

class C2(C1):
    def __init__(self): #overrides C1.__init__
        print "C2 init"
        C1.__init__(self) #but we still want C1 to init the class too
>>> C2()
"C2 init"
"C1 init"

As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call Class.some_method(inst).

An example of where it’s useful:

class C1(object):
    def __init__(self):
         print "C1 init"

class C2(C1):
    def __init__(self): #overrides C1.__init__
        print "C2 init"
        C1.__init__(self) #but we still want C1 to init the class too
>>> C2()
"C2 init"
"C1 init"

回答 8

它的使用类似于thisJava 中关键字的使用,即提供对当前对象的引用。

Its use is similar to the use of this keyword in Java, i.e. to give a reference to the current object.


回答 9

与Java或C ++不同,Python不是为面向对象编程而构建的语言。

在Python中调用静态方法时,只需编写一个内部带有常规参数的方法。

class Animal():
    def staticMethod():
        print "This is a static method"

但是,对象方法需要您创建一个变量,在这种情况下,该方法是动物,需要使用self参数

class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"

self方法还用于引用类中的变量字段。

class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";


    def getAnimalName(self):
        return self.animalName

在这种情况下,self指的是整个类的animalName变量。记住:如果方法中有变量,则self将不起作用。该变量仅在该方法运行时才存在。为了定义字段(整个类的变量),您必须在类方法之外定义它们。

如果您听不懂我在说什么,请使用Google“面向对象编程”。一旦理解了这一点,您甚至不需要问这个问题:)。

Python is not a language built for Object Oriented Programming unlike Java or C++.

When calling a static method in Python, one simply writes a method with regular arguments inside it.

class Animal():
    def staticMethod():
        print "This is a static method"

However, an object method, which requires you to make a variable, which is an Animal, in this case, needs the self argument

class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"

The self method is also used to refer to a variable field within the class.

class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";


    def getAnimalName(self):
        return self.animalName

In this case, self is referring to the animalName variable of the entire class. REMEMBER: If you have a variable within a method, self will not work. That variable is simply existent only while that method is running. For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods.

If you don’t understand a single word of what I am saying, then Google “Object Oriented Programming.” Once you understand this, you won’t even need to ask that question :).


回答 10

可以遵循Python禅宗的“显式优于隐式”的说法。它确实是对您的类对象的引用。例如,在Java和PHP中,它称为this

如果user_type_name模型上的字段为,则可以通过进行访问self.user_type_name

It’s there to follow the Python zen “explicit is better than implicit”. It’s indeed a reference to your class object. In Java and PHP, for example, it’s called this.

If user_type_name is a field on your model you access it by self.user_type_name.


回答 11

首先,自我是一个常规名称,您可以代之以其他任何东西(连贯一致)。

它指的是对象本身,因此,在使用它时,您声明.name和.age是要创建的Student对象的属性(注意,不是Student类的属性)。

class Student:
    #called each time you create a new Student instance
    def __init__(self,name,age): #special method to initialize
        self.name=name
        self.age=age

    def __str__(self): #special method called for example when you use print
        return "Student %s is %s years old" %(self.name,self.age)

    def call(self, msg): #silly example for custom method
        return ("Hey, %s! "+msg) %self.name

#initializing two instances of the student class
bob=Student("Bob",20)
alice=Student("Alice",19)

#using them
print bob.name
print bob.age
print alice #this one only works if you define the __str__ method
print alice.call("Come here!") #notice you don't put a value for self

#you can modify attributes, like when alice ages
alice.age=20
print alice

代码在这里

First of all, self is a conventional name, you could put anything else (being coherent) in its stead.

It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.

class Student:
    #called each time you create a new Student instance
    def __init__(self,name,age): #special method to initialize
        self.name=name
        self.age=age

    def __str__(self): #special method called for example when you use print
        return "Student %s is %s years old" %(self.name,self.age)

    def call(self, msg): #silly example for custom method
        return ("Hey, %s! "+msg) %self.name

#initializing two instances of the student class
bob=Student("Bob",20)
alice=Student("Alice",19)

#using them
print bob.name
print bob.age
print alice #this one only works if you define the __str__ method
print alice.call("Come here!") #notice you don't put a value for self

#you can modify attributes, like when alice ages
alice.age=20
print alice

Code is here


回答 12

self是对对象本身的对象引用,因此它们是相同的。在对象本身的上下文中未调用Python方法。 self在Python中,可能用于处理自定义对象模型之类的东西。

self is an object reference to the object itself, therefore, they are same. Python methods are not called in the context of the object itself. self in Python may be used to deal with custom object models or something.


回答 13

使用通常称为参数的参数self并不难理解,为什么要这样做呢?还是关于为什么要明确提及?我想,对于大多数查询此问题的用户来说,这是一个更大的问题,或者如果不是,则在继续学习python时,他们肯定会遇到相同的问题。我建议他们阅读以下两个博客:

1:自我解释

请注意,它不是关键字。

每个类方法(包括init)的第一个参数始终是对当前类实例的引用。按照惯例,此参数始终命名为self。在init方法中,self指的是新创建的对象;在其他类方法中,它引用其方法被调用的实例。例如,下面的代码与上面的代码相同。

2:为什么要用这种方式,为什么不能像Java那样将其作为参数消除,而要用关键字代替

我想补充的另一件事是,可选self参数允许我通过不编写而在类内声明静态方法self

代码示例:

class MyClass():
    def staticMethod():
        print "This is a static method"

    def objectMethod(self):
        print "This is an object method which needs an instance of a class, and that is what self refers to"

聚苯乙烯:仅在Python 3.x中有效。

在以前的版本中,必须显式添加@staticmethod装饰器,否则self必须使用参数。

The use of the argument, conventionally called self isn’t as hard to understand, as is why is it necessary? Or as to why explicitly mention it? That, I suppose, is a bigger question for most users who look up this question, or if it is not, they will certainly have the same question as they move forward learning python. I recommend them to read these couple of blogs:

1: Use of self explained

Note that it is not a keyword.

The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.

2: Why do we have it this way and why can we not eliminate it as an argument, like Java, and have a keyword instead

Another thing I would like to add is, an optional self argument allows me to declare static methods inside a class, by not writing self.

Code examples:

class MyClass():
    def staticMethod():
        print "This is a static method"

    def objectMethod(self):
        print "This is an object method which needs an instance of a class, and that is what self refers to"

PS:This works only in Python 3.x.

In previous versions, you have to explicitly add @staticmethod decorator, otherwise self argument is obligatory.


回答 14

我很惊讶没有人提出Lua。Lua也使用’self’变量,但是可以省略但仍然使用。C ++对“ this”的作用相同。我没有看到任何理由必须在每个函数中声明“ self”,但是您仍然应该能够像在lua和C ++中一样使用它。对于一种以简短为荣的语言,奇怪的是它要求您声明自变量。

I’m surprised nobody has brought up Lua. Lua also uses the ‘self’ variable however it can be omitted but still used. C++ does the same with ‘this’. I don’t see any reason to have to declare ‘self’ in each function but you should still be able to use it just like you can with lua and C++. For a language that prides itself on being brief it’s odd that it requires you to declare the self variable.


回答 15

请看以下示例,该示例清楚地说明了 self

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True

>>> x.bankrupt
False  

self 用于/需要区分实例。

资料来源:python中的self变量解释-Pythontips

Take a look at the following example, which clearly explains the purpose of self

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True

>>> x.bankrupt
False  

self is used/needed to distinguish between instances.

Source: self variable in python explained – Pythontips


回答 16

是因为按照python的设计方式,替代方法几乎行不通。Python旨在允许在无法使用隐式this(a-la Java / C ++)或显式@(a-la ruby​​)的上下文中定义方法或函数。我们来看一个使用python约定的显式方法的示例:

def fubar(x):
    self.x = x

class C:
    frob = fubar

现在,该fubar功能将无法使用,因为它将假定它self是一个全局变量(以及in frob)。另一种方法是执行具有替换后的全局范围的方法(其中self对象)。

隐式方法是

def fubar(x)
    myX = x

class C:
    frob = fubar

这意味着myX它将被解释为fubarfrob以及)中的局部变量。这里的替代方法是执行具有替换的局部作用域的方法,该局部作用域在调用之间保留,但是这将消除方法局部变量的可能性。

但是,目前的情况很好:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

这里的时候,被称为一方法frob将接收上它通过调用对象self的参数,并且fubar仍然可以用一个对象作为参数调用和工作一样(这一样的C.frob,我认为)。

Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this (a-la Java/C++) or explicit @ (a-la ruby) wouldn’t work. Let’s have an example with the explicit approach with python conventions:

def fubar(x):
    self.x = x

class C:
    frob = fubar

Now the fubar function wouldn’t work since it would assume that self is a global variable (and in frob as well). The alternative would be to execute method’s with a replaced global scope (where self is the object).

The implicit approach would be

def fubar(x)
    myX = x

class C:
    frob = fubar

This would mean that myX would be interpreted as a local variable in fubar (and in frob as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.

However the current situation works out well:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

here when called as a method frob will receive the object on which it’s called via the self parameter, and fubar can still be called with an object as parameter and work the same (it is the same as C.frob I think).


回答 17

在该__init__方法中,self指的是新创建的对象;在其他类方法中,它引用其方法被调用的实例。

自我,正如名字一样,只是一个约定,可以随意称呼它!但是在使用它(例如删除对象)时,必须使用相同的名称:__del__(var),其中var在使用__init__(var,[...])

您也应该看一下cls,以了解更大的情况。这篇文章可能会有所帮助。

In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var), where var was used in the __init__(var,[...])

You should take a look at cls too, to have the bigger picture. This post could be helpful.


回答 18

self的作用类似于当前的对象名称或class的实例。

# Self explanation.


 class classname(object):

    def __init__(self,name):

        self.name=name
        # Self is acting as a replacement of object name.
        #self.name=object1.name

   def display(self):
      print("Name of the person is :",self.name)
      print("object name:",object1.name)


 object1=classname("Bucky")
 object2=classname("ford")

 object1.display()
 object2.display()

###### Output 
Name of the person is : Bucky
object name: Bucky
Name of the person is : ford
object name: Bucky

self is acting as like current object name or instance of class .

# Self explanation.


 class classname(object):

    def __init__(self,name):

        self.name=name
        # Self is acting as a replacement of object name.
        #self.name=object1.name

   def display(self):
      print("Name of the person is :",self.name)
      print("object name:",object1.name)


 object1=classname("Bucky")
 object2=classname("ford")

 object1.display()
 object2.display()

###### Output 
Name of the person is : Bucky
object name: Bucky
Name of the person is : ford
object name: Bucky

回答 19

self 是不可避免的。

只是有一个问题应该self是隐性或显性的。 Guido van Rossum解决了这个问题,说self必须留下

那么self住在哪里?

如果我们只是坚持使用函数式编程,那就不需要了self。进入Python OOP之后,我们发现self其中。

这是class C该方法的典型用例m1

class C:
    def m1(self, arg):
        print(self, ' inside')
        pass

ci =C()
print(ci, ' outside')
ci.m1(None)
print(hex(id(ci))) # hex memory address

该程序将输出:

<__main__.C object at 0x000002B9D79C6CC0>  outside
<__main__.C object at 0x000002B9D79C6CC0>  inside
0x2b9d79c6cc0

因此self保留了类实例的内存地址。 的目的self实例方法保留引用,并让我们可以显式访问该引用。


请注意,有三种不同类型的类方法:

  • 静态方法(阅读:函数),
  • 类方法
  • 实例方法(提到)。

self is inevitable.

There was just a question should self be implicit or explicit. Guido van Rossum resolved this question saying self has to stay.

So where the self live?

If we would just stick to functional programming we would not need self. Once we enter the Python OOP we find self there.

Here is the typical use case class C with the method m1

class C:
    def m1(self, arg):
        print(self, ' inside')
        pass

ci =C()
print(ci, ' outside')
ci.m1(None)
print(hex(id(ci))) # hex memory address

This program will output:

<__main__.C object at 0x000002B9D79C6CC0>  outside
<__main__.C object at 0x000002B9D79C6CC0>  inside
0x2b9d79c6cc0

So self holds the memory address of the class instance. The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.


Note there are three different types of class methods:

  • static methods (read: functions),
  • class methods,
  • instance methods (mentioned).

回答 20

文档

方法的特殊之处在于,实例对象作为函数的第一个参数传递。在我们的示例中,该调用x.f()与完全等效MyClass.f(x)。通常,调用带有n个参数列表的方法等同于调用带有参数列表的函数,该参数列表是通过在第一个参数之前插入方法的实例对象而创建的。

在相关片段之前,

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

x = MyClass()

from the docs,

the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.

preceding this the related snippet,

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

x = MyClass()


回答 21

它是对类实例对象的显式引用。

it’s an explicit reference to the class instance object.