想想这个例子:

class MyClass:
    def func(self, name):
        self.name = name

我知道self引用MyClass的特定实例。但是为什么func必须显式地包含self作为参数呢?为什么我们需要在方法的代码中使用self ?其他一些语言将其隐式化,或者使用特殊的语法。


有关设计决策的语言无关性考虑,请参见强制显式使用this/self指针的好处是什么?

要关闭OP省略方法的self形参并获得TypeError的调试问题,请使用TypeError: method()接受1个位置参数,但给出了2个。如果OP省略了self。在方法体中得到一个NameError,考虑如何在类中调用函数?


当前回答

The reason you need to use self. is because Python does not use special 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..

其他回答

Self是对对象本身的引用,因此,它们是相同的。 Python方法不是在对象本身的上下文中调用的。 self在Python中可以用来处理自定义对象模型或其他东西。

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

因此,对象的数据被绑定到对象上。下面是一个示例,说明您可能希望如何可视化每个对象的数据。注意“self”是如何被对象名称替换的。我并不是说下面这个示例图是完全准确的,但希望它能在可视化self的使用方面起到一定的作用。

对象被传递到self参数中,这样对象就可以保存自己的数据。

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.

如下图所示:

从医生那里,

方法的特殊之处在于实例对象是作为函数的第一个参数传递的。在我们的例子中,调用x.f()完全等价于MyClass.f(x)。一般来说,调用带有n个参数列表的方法相当于调用带有参数列表的相应函数,该参数列表是通过在第一个参数之前插入方法的实例对象创建的。

在此之前的相关片段,

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

    def f(self):
        return 'hello world'

x = 我的类()

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

看看下面的例子,它清楚地解释了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