想想这个例子:
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文档:
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类文档教程。
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..
假设你有一个类ClassA,它包含一个方法methodA,定义为:
def methodA(self, arg1, arg2):
# do something
objectA是这个类的一个实例。
现在当objectA。当调用methodA(arg1, arg2)时,python会在内部将其转换为:
ClassA.methodA(objectA, arg1, arg2)
self变量引用对象本身。
自我是不可避免的。
问题是,self是隐式的还是显式的。
Guido van Rossum解决了这个问题说self必须留下来。
那么自我生活在哪里呢?
如果我们坚持函数式编程,我们就不需要self了。
一旦我们进入Python OOP,我们就会发现自己在那里。
下面是带有方法m1的典型用例类C
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的目的是保存实例方法的引用,并使我们能够显式地访问该引用。
注意有三种不同类型的类方法:
静态方法(读作:函数),
类方法,
实例方法(已提到)。