问题描述
self
在 Python 中的作用是什么?我知道它指的是从该类创建的特定对象,但我不明白为什么需要将它作为参数明确添加到每个函数中.为了说明,在 Ruby 中我可以这样做:
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
我很容易理解.但是在 Python 中我需要包含 self
:
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.
推荐答案
需要使用 self.
的原因是因为 Python 没有使用 @
语法来引用到实例属性.Python 决定以一种方式执行方法,使方法所属的实例自动传递,而不是自动接收:方法的第一个参数是方法的实例被调用.这使得方法与函数完全相同,并让实际名称由您自己决定(尽管 self
是约定俗成的,当您使用其他东西时,人们通常会对您皱眉.)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 可以做一些其他的事情来区分普通名称和属性——像 Ruby 那样的特殊语法,或者像 C++ 和 Java 那样需要声明,或者可能是更不同的东西——但它没有.Python 就是为了让事情变得明确,让什么是什么变得显而易见,虽然它没有在所有地方都这样做,但它确实在实例属性方面做到了这一点.这就是为什么分配给实例属性需要知道要分配给哪个实例,这就是为什么它需要 self.
.
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.
.
这篇关于“自我"这个词的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!