The reason you need to use self.
(您需要使用self.
的原因self.
)
is because Python does not use the @
syntax to refer to instance attributes. (这是因为Python不使用@
语法来引用实例属性。)
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. (Python决定以一种使该方法所属的实例自动传递但不会自动接收的方式进行方法:方法的第一个参数是调用该方法的实例。)
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. (这使得方法与函数完全相同,并保留实际名称供您使用(尽管self
是惯例,当您使用其他东西时,人们通常会对您皱眉。) 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可以做一些其他事情来区分普通名称和属性-像Ruby这样的特殊语法,或者像C ++和Java这样的声明都需要,或者也许还有其他不同-但事实并非如此。)
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. (Python的全部目的是使事情变得明确,使事情变得显而易见,尽管它并非在所有地方都做到这一点,但它确实为实例属性做到了。)
That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self.
(这就是为什么分配给实例属性需要知道要分配给哪个实例的原因,这就是为什么它需要self.
的原因self.
)
. (。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…