Python/Java 类型转换¶
Jython会自动处理Java和Python之间的类型转换。然而,了解Python类型与Java类型的对应关系是很有用的。下表描述了Python中所有类型与它们的Java对应类型之间的对应关系。
| Python Type | Jython PyObject Subclass | Java Type | Description |
|---|---|---|---|
int |
PyInteger |
java.lang.Integer |
将 Python 的 int 映射到 Java 的 Integer。 |
float |
PyFloat |
java.lang.Double |
将 Python 的 float 映射到 Java 的 Double。 |
str |
PyString |
java.lang.String |
将 Python 的 str 映射到 Java 的 String。 |
bool |
PyBoolean |
java.lang.Boolean |
将 Python 的 True/False 映射到 Java 的 Boolean。 |
None |
PyNone |
null |
Python 的 None 转换成 Java 的 null。 |
long (Python 2 only) |
PyLong |
java.math.BigInteger |
将 Python 的 long 映射到 BigInteger。 |
complex |
PyComplex |
org.python.core.PyComplex |
代表复数。 |
list |
PyList |
java.util.List |
将 Python 的 list 映射到 Java 的 List。 |
tuple |
PyTuple |
java.util.List (不可变) |
将 Python 的 tuple 映射到 Java 的 List,但是不可变。 |
dict |
PyDictionary |
java.util.Map |
将 Python 的 dict 映射到 Java 的 Map。 |
set |
PySet |
java.util.Set |
将 Python 的 set 映射到 Java 的 Set。 |
frozenset |
PyFrozenSet |
java.util.Set (不可变) |
将 Python 的 frozenset 映射到不可变的 Java Set。 |
bytes |
PyString |
byte[] |
将 Python 的 bytes 映射到 Java 的 byte[]。 |
bytearray |
PyByteArray |
byte[] |
bytes 的可变版本映射到 byte[]。 |
memoryview |
PyMemoryView |
org.python.core.PyMemoryView |
将 Python 的 memoryview 映射到 Java 的 PyMemoryView。 |
function |
PyFunction |
org.python.core.PyFunction |
Python 函数映射到 Java 的 PyFunction。 |
method |
PyMethod |
org.python.core.PyMethod |
Python 方法映射到 PyMethod。 |
class |
PyClass |
org.python.core.PyClass |
在 Java 中表示 Python 类。 |
instance |
PyInstance |
org.python.core.PyInstance |
将 Python 实例映射到 PyInstance。 |
module |
PyModule |
org.python.core.PyModule |
在 Jython 中表示 Python 模块。 |
callable (例如,lambda函数) |
PyCallable |
org.python.core.PyObject (callable) |
将可调用的 Python 对象如 lambda 函数映射到 Java。 |
object (通用) |
PyObject |
java.lang.Object |
通用的 Python 对象映射到 Java 的 Object。 |
iter (迭代器) |
PyIterator |
java.util.Iterator |
Python 的 iterator 映射到 Java 的 Iterator。 |
generator |
PyGenerator |
org.python.core.PyGenerator |
将 Python 的生成器对象映射到 Java。 |
Exception |
PyException |
java.lang.Throwable |
Python 异常映射到 Java 的 Throwable。 |
file (仅 Python 2) |
PyFile |
java.io.InputStream/OutputStream |
将 Python 的文件对象映射到 Java IO 流。 |
ellipsis (...) |
PyEllipsis |
org.python.core.PyEllipsis |
代表 Python 中的 ... 对象。 |
NotImplemented |
PyNotImplemented |
org.python.core.PyNotImplemented |
代表 Python 中的 NotImplemented。 |
slice |
PySlice |
org.python.core.PySlice |
代表 Python 切片。 |
buffer (仅 Python 2) |
PyBuffer |
org.python.core.PyBuffer |
代表 Python 缓冲区对象。 |
type (元类) |
PyType |
org.python.core.PyType |
在 Java 中映射 Python 元类 (type)。 |
自定义对象 |
用户定义的 PyObject |
用户定义的 Java 类或接口 | 自定义的 Python 类映射到 Java 的 PyObject。 |