Skip to main content
 首页 » 编程设计

python之"a type/class/function/module/... object"的含义

2025年05月04日10qq号

当我阅读 Python in a Nutshell 时,我看到了“类型对象”、“类对象”、“函数对象”、“模块对象”……

“xxx 对象”是否表示类型为“xxx”的实例?

例如,

  • 类型对象是否意味着类型 type 的实例?例如,int 是类型对象吗?特定类是类型对象吗?

  • 类对象是指什么的实例?特定类是类对象吗?例如,

    A class is a Python object with several characteristics:

    • You can call a class object as if it were a function. The call, often known as instantiation, returns an object known as an instance of the class; the class is known as the type of the instance.

    • A class can inherit from other classes, meaning it delegates to other class objects the lookup of attributes that are not found in the class itself.

  • 函数对象是否意味着 types.FunctionType 的实例?特定函数是函数对象吗?

  • 模块对象是否意味着 types.ModuleType 的实例?特定模块是模块对象吗?

  • 是否有 int 对象?如果是,是否表示 int 类型的整数值(例如 12)?

谢谢。

请您参考如下方法:

Does a type object mean an instance of type type? For example, is int a type object? Ιs a specific class a type object?

是的,“类型”对象是指“类型”类型的对象,因此是该类型的实例。始终可以使用 isinstance 检查有关某物是什么类型的信息。要回答你的第二个问题,int 是 type 类型的对象吗:

>>> isinstance(int, type) # True 

是自定义类类型的对象:

>>> class Spammy:  
...     pass 
>>> isinstance(Spammy, type) 
True 

Does a class object mean an instance of what? Is a specific class a class object?

类对象的使用可与 Unification of types and classes 之后的术语 type object 互换。在 Python 2.2 中。术语“类”主要用于指代用户定义的类(您使用 class 语句创建的类),但它实际上意味着同一件事。

这确实在具有旧样式类的 Python 2 中有所不同。未从类定义中的对象继承得到类型为 classobj 的对象:

>>> class Foo: 
...     pass 
>>> type(Foo) 
<type 'classobj'> 

这在 Python 3 中不存在,其中所有类都是 type 类型的对象。

Does a function object mean an instance of types.FunctionType? Is a specific function a function object?

Does a module object mean an instance of types.ModuleType? Is a specific module a module object?

对所有这些都是肯定的:

>>> def foo(): pass 
>>> type(foo)   
function  
>>> import collections     
>>> type(collections) 
module 

Is there an int object? If yes, does it mean an integer value (e.g. 12) of type int?

有一个int类型,它是一个类型对象和一个int对象,它是一个int类型的对象。 12 就是一个例子,因为:

>>> type(12) 
int  

同时,int 上同样的事情产生:

>>> type(int) 
type