Python self和Java之间的区别 [英] Difference between Python self and Java this

查看:574
本文介绍了Python self和Java之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我早就做了一点Python。然而,我现在转向Java。我想知道Pythonself方法和Javathis之间是否存在任何差异。

I had done a bit of Python long back. I am however moving over to Java now. I wanted to know if there were any differences between the Python "self" method and Java "this".

我知道self不是关键词而this 是的。这几乎是我能想到的。我错过了什么吗?

I know that "self" is not a keyword while "this" is. And that is pretty much what I could figure out. Am I missing anything else?

推荐答案

关于自我 in Python(这里是来源: Python自我解释):

About self in Python (here is the source: Python self explanation):

您需要使用 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..

关于Oracle解释了Java中的这个(这里是来源: Java这个解释):

About this in Java being explained by Oracle (here is the source: Java this explanation):

在实例方法或构造函数中, this 是对当前对象的引用 - 正在调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。
使用 this 关键字的最常见原因是因为某个字段被方法或构造函数参数遮蔽。

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

这篇关于Python self和Java之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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