Python 把“数据”和“行为”统一成对象模型,所以“基本数据”就是类;而 Java 把“值”和“对象”分裂成两套体系,因此有了“基本类型 vs 包装类”的区别。
Python 的“一切皆对象”哲学 在 Python 里,变量只是名字→对象的引用。 即使是 3 这样的字面量,运行时也会当场创建一个 int 实例,并返回它的地址:
>>> import sys
>>> sys.getrefcount(3) # 3 这个对象真的存在
39
>>> type(3)
<class 'int'>
在 Python 里 int
、str
、list
等名字同时扮演三种角色
类型名(type name):
>>> type(3) <class 'int'>
类名(class name)
它们是实实在在定义在解释器里的类,可以拿来继承、实例化、反射:
>>> issubclass(bool, int) # 继承关系 True >>> isinstance([1, 2], list) True
类对象本身(class object)
名字 int
、str
、list
在运行时就是一堆属性、方法的容器,本身就是一个“对象”:
>>> int.__doc__ # 类的属性 "int([x]) -> integer..." >>> list.__base__ # 查看基类 <class 'object'>
int
、str
、list
既是类型名,也是类名,更是可操作的类对象
>>> issubclass(bool, int)bool
这个类是int
这个类的子类(派生类) True >>> int.__bases__ (<class 'object'>,)
byte short int long float double char boolean
Byte Short Integer Long Float Double Character Boolean
java.lang
,具有方法和字段。Integer x = 3; // 自动装箱:int → Integer int y = x + 1; // 自动拆箱:Integer → int
但底层仍是两种完全不同的东西
int a = 3; Integer b = 3; System.out.println(a == b); // true:b 先拆箱再比较值 System.out.println(a.getClass()); // 编译错误:int 没有类 System.out.println(b.getClass()); // class java.lang.Integer
python14种基本数据类型:
3 → 实例对象 ↑ int → 类对象(由 type 生成) ↑ type → 元类(metaclass) ↑ object → 所有类的最终祖先 int、str、list 这些“类对象”本身是由 type 这个类实例化出来的。 >>> type(3) # 实例对象的类型 <class 'int'> >>> type(int) # 类对象 int 的类型 <class 'type'> >>> type(type) # type 自己的类型 <class 'type'> >>> type.__bases__ # type 的基类 (<class 'object'>,) >>> object.__bases__ # object 没有基类 ()
类名(...)
这种语法),那么 全部都有。__init__
,那么逻辑上它们都有,只不过很多内置类的 __init__
是用 C 写的、对用户不可见,或者和 __new__
合并在一起了类型 | 常用构造示例 |
---|---|
int | int(x=0, base=10) |
float | float(x=0) |
complex | complex(real=0, imag=0) |
bool | bool(x=False) |
str | str(object='', encoding='utf-8', errors='strict') |
bytes | bytes(source, encoding='utf-8', errors='strict') |
bytearray | bytearray(source) |
list | list(iterable=[]) |
tuple | tuple(iterable=[]) |
range | range(stop) / range(start, stop, step) |
set | set(iterable=[]) |
frozenset | frozenset(iterable=[]) |
dict | dict(**kw) / dict(mapping) / dict(iterable) |
memoryview | memoryview(obj) |