想想这个例子:

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


当前回答

这个参数的使用,通常称为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"

PS:这只适用于Python 3.x。

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

其他回答

我的小钱

在Person类中,我们用self定义了init方法,这里需要注意的有趣的事情是self和实例变量p的内存位置是相同的<__main__。位于0x106a78fd0>的Person对象

class Person:

    def __init__(self, name, age):
        self.name = name 
        self.age = age 

    def say_hi(self):
        print("the self is at:", self)
        print((f"hey there, my name is {self.name} and I am {self.age} years old"))

    def say_bye(self):
        print("the self is at:", self)
        print(f"good to see you {self.name}")

p = Person("john", 78)
print("the p is at",p)
p.say_hi()  
p.say_bye() 

如上所述,self和实例变量都是同一个对象。

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

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

objectA是这个类的一个实例。

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

ClassA.methodA(objectA, arg1, arg2)

self变量引用对象本身。

它的使用类似于Java中this关键字的使用,即给出对当前对象的引用。

当对象实例化时,对象本身被传递到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.

如下图所示:

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

自我,作为一个名字,只是一个惯例,你想怎么叫就怎么叫!但是当使用它时,例如删除对象,你必须使用相同的名称:__del__(var),其中var在__init__(var,[…])中使用。

你也应该看一看cls,以获得更大的图景。这篇文章可能会有帮助。