gpt4 book ai didi

java - 类成员——Java 与 Python

转载 作者:太空狗 更新时间:2023-10-29 20:27:10 26 4
gpt4 key购买 nike

我来自 Java,现在正在学习 Python。我尝试理解 Python 中类成员的概念。

这是 Java 中的示例程序:

class Hello {
int x = 0;

void ex() {
x = 7;
}

public static void main(String args[]) {
Hello h = new Hello();
System.out.println(h.x);
h.ex();
System.out.println(h.x);
} }

这就是我在 Python 中所做的,遵循我发现的一些示例:

class Hello:
def __init__(self) :
self.x = 0

def ex(self):
self.x = 7

h = Hello()
print(h.x)
h.ex()
print(h.x)

两个程序都返回:

0
7

这是我的问题:

  1. Python 代码是否正确?
  2. 与 Java 相比,Python 的编程风格在我看来更为紧凑。所以我想知道,为什么 Python 需要传递“ self ”-- 参数。
  3. 在这一点上,Python 似乎比 Java 更“复杂”。或者有没有办法删除“self”-- 参数?

最佳答案

首先,你的python代码是正确的。

这只是语言如何设计的问题。 Java 使用一种对对象引用的自动推断。对于非 Java 专家,它有时会导致奇怪的行为:

private int a; 
public int add(int a, int b){
return a+b; // what a will it use?
}

所以,这就是为什么在 java 中有关键字 this 可以使用(但你不是被迫的)来解决这种歧义。

python 团队决定强制使用单词 self(或任何其他单词,但我稍后会解释)以避免此类问题。你无法摆脱它。尽管如此,java 仍然是一种比 python 更冗长的语言,关键字 self 不会对这个假设产生太大影响。

但是,您不必使用“self”一词作为对当前对象的引用。您可以使用任何其他词作为您方法的第一个参数(但这是一种非常糟糕的做法)。

在这里,你可以看到两个引用文献,深刻解释了为什么“ self 在这里停留”:

http://www.programiz.com/article/python-self-why

http://neopythonic.blogspot.be/2008/10/why-explicit-self-has-to-stay.html

关于java - 类成员——Java 与 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com