“自我"一词的目的是什么? [英] What is the purpose of the word 'self'?

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

问题描述

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,当您使用其他名称时,人们通常会皱着眉头.)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天全站免登陆