想想这个例子:

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,考虑如何在类中调用函数?


当前回答

假设你有一个类ClassA,它包含一个方法methodA,定义为:

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

objectA是这个类的一个实例。

现在当objectA。当调用methodA(arg1, arg2)时,python会在内部将其转换为:

ClassA.methodA(objectA, arg1, arg2)

self变量引用对象本身。

其他回答

这是为了遵循Python的禅宗“显式优于隐式”。它实际上是对类对象的引用。例如,在Java和PHP中,它被称为this。

如果user_type_name是你的模型中的一个字段,你可以通过self.user_type_name访问它。

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

以下摘自关于self的Python文档:

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.

有关更多信息,请参阅Python类文档教程。

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

我很惊讶居然没人提起Lua。Lua也使用“self”变量,但是可以省略,但仍然使用。c++对'this'做了同样的处理。我不认为有任何理由必须在每个函数中声明“self”,但你仍然可以像使用lua和c++一样使用它。对于一门以简洁为傲的语言来说,它要求你声明self变量是很奇怪的。