Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - Python中“自我”一词的目的是什么?(What is the purpose of the word 'self', in Python?)

What is the purpose of the self word in Python?

(Python中self词的目的是什么?)

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:

(为了说明这一点,在Ruby中,我可以这样做:)

class myClass
    def myFunc(name)
        @name = name
    end
end

Which I understand, quite easily.

(我很容易理解。)

However in Python I need to include self :

(但是在Python中,我需要包含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.

(我的经历(公认有限)并不是我遇到的。)

  ask by richzilla translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

.

(。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...