自我的目的是什么? [英] What is the purpose of self?

查看:156
本文介绍了自我的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中 self 的目的是什么?我理解它指的是从该类创建的特定对象,但我不明白为什么它明确需要添加到每个函数作为参数。为了说明,在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 是约定,人们一般会皱眉你在你使用东西

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..

这篇关于自我的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆