object 是 Python 所有类的根类,提供默认方法并构成类型系统基础。
基本概念
- 所有类的终极父类
- Python 3 中
class Foo: 等价于 class Foo(object): - Python 2 需显式继承才能使用新式类
核心作用
提供基础方法
| 方法 | 作用 |
|---|
__init__ | 构造函数 |
__str__ | 字符串表示(print(obj)) |
__eq__ | 相等比较(==) |
__hash__ | 支持作为字典键 |
类型系统基础
1
2
| isinstance(42, object) # True
issubclass(int, object) # True
|
实际用途
1
2
3
4
5
6
7
8
9
10
11
| # 通用类型提示
def func(arg: object) -> None: ...
# 重载默认方法
class Person:
def __str__(self):
return "Person"
# 检查基类
class Foo: pass
Foo.__bases__ # (<class 'object'>,)
|
与 type 的关系
1
2
| isinstance(object, type) # True(object 是 type 的实例)
isinstance(type, object) # True(type 是 object 的子类)
|
object:所有类的父类type:所有类的元类(包括 object 本身)
Comments