我正在尝试利用现有的 Python 知识来学习 Java。我知道 Java 对象可以具有 toString()
方法,就像 Python 对象具有 __str__()
方法一样,但我不知道如何实现以同样的方式翻译 Python 的 __int__()
。
下面是我尝试将代码转换为 Java 的 Python 等效代码:
class Robot:
def __init__(self):
pass
def __int__(self):
return 12
print(int(Robot())) # Should print 12.
最佳答案
Python 中的 __int__
方法允许将 class
插入到语言内置的 int()
功能中 - 进行“解析”任意 class
的实例到 int
。
Java 中没有等效的结构,但您可以创建一个类似的构造。这需要你明确表达。
public class Robot {
private int serial;
//ctor, getters, setters etc etc
public int toInt() {
return serial;
}
public static int toInt(Robot robot) {
return robot.toInt();
}
}
然后你可以做类似的事情
//some class, synax elided
import static com.pkg.Robot.toInt;
System.out.println(toInt(new Robot()));
由于 Java 中没有 int()
功能,因此这并不能真正为您提供太多帮助:
System.out.println(new Robot().toInt());
或者更清楚:
System.out.println(new Robot().getSerial());
<小时/>
如果您想要更通用的东西,您可以创建一个界面
:
public interface Intable {
int toInt();
}
然后,您可以在您认为应该能够将自身转变为 int
的类中实现
Interface
。
关于Python 的 __int__() 的 Java 对象方法 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785573/