3. 一切皆对象

不知道大家有没有注意到, 在Section 2 中, 我说当执行 a = 1 时, 是将引用符号 a 指向了 1 这个对象. 不知道读者是否有过疑问, 在 Python 中, 1 也是一个对象吗?

是的. 在 Python 中, 一切都是对象. Python 在面向对象方面, 贯彻的非常彻底.

我们可以看一下Listing 3.1, 整数 1 是有成员方法 __dir__ 的, 而且成员方法 __dir__ 的返回值是该对象的所有成员名称.

Listing 3.1 examples/object/all_are_objects/members_of_int.py
print(f'there are {len((1).__dir__())} members of int')
print(f'they are {", ".join((1).__dir__()[:4])}, ...')
print(f'the class of {repr(1)} is {(1).__class__.__name__}')

Listing 3.1 的执行结果如下所示.

$ python3 examples/object/all_are_objects/members_of_int.py
there are 71 members of int
they are __repr__, __hash__, __getattribute__, __lt__, ...
the class of 1 is int

从上面这个例子我们可以看出来, 简单如整数 int, 在 Python 中都是对象.

我们知道, 在面向对象编程中, 对象是类 class 的实例, 那么, class 难道也是对象?

是的!

Listing 3.2 examples/object/all_are_objects/class_is_object.py
class A: pass

print(f'is class an object? {isinstance(A, object)}')
print(f'the type of class A is {A.__class__.__name__}')
$ python3 examples/object/all_are_objects/class_is_object.py
is class an object? True
the type of class A is type

有的人会有疑问: 那函数也是对象? 必须的!

Listing 3.3 examples/object/all_are_objects/function_is_object.py
def a(): pass
b = lambda: None

print(f'is function a an object? {isinstance(a, object)}')
print(f'the type of function a is {a.__class__.__name__}')
print(f'is function b an object? {isinstance(a, object)}')
print(f'the type of function b is {b.__class__.__name__}')
$ python3 examples/object/all_are_objects/function_is_object.py
is function a an object? True
the type of function a is function
is function b an object? True
the type of function b is function

深度思考

可否实现一个对象 obj, 使得 isinstance(obj, object) 的值是 False?