python中内置关键字type是指函数还是类?

Myr*_*rfy 4 python types metaclass

在大多数帖子中,人们经常说type如果提供一个参数,则它是一个内置函数;如果提供 3 个参数,则它是一个元类。

但在python 的 doc中, 的签名type是:

class type(object)
class type(name, bases, dict)
Run Code Online (Sandbox Code Playgroud)

那么,type即使它提供了一个参数,这是否意味着它是一个内置类而不是一个内置函数?

小智 6

type被称为“元类”,因为它是生成其他类(又称类型)的类。它的行为就像一个普通的类。特别是,它具有__new__相当于 Python 中如下所示的方法:

class type(object):

    def __new__(cls, *args):
        num_args = len(args)

        if num_args not in (1, 3):
            raise TypeError('type() takes 1 or 3 arguments')

        # type(x)
        if num_args == 1:
            return args[0].__class__

        # type(name, bases, dict)
        name, bases, attributes = args
        bases = bases or (object,)

        class Type(*bases):
            pass

        Type.__name__ = name

        qualpath = Type.__qualname__.rsplit('.', 1)[0]
        Type.__qualname__ = '.'.join((qualpath, name))

        for name, value in attributes.items():
            setattr(Type, name, value)

        return Type

Class = type('Class', (), {'i': 1})
instance = Class()

print(type(instance))  # -> Class
print(instance.__class__)  # -> Class
print(type(type(instance)))  # -> type
print(Class.i)  # -> 1
print(instance.i)  # -> 1
Run Code Online (Sandbox Code Playgroud)

请注意,实例化类时,新实例的值是从__new__. 在 的情况下type__new__始终返回类型对象(也称为类)。int下面是一个扩展为用作-1默认值而不是 的类的示例0

def Int__new__(cls, *args):
    if not args:
        return cls(-1)
    return super(cls, cls).__new__(cls, *args)

Int = type('Int', (int,), {'__new__': Int__new__})

i = Int()
print(type(i))  # -> Int
print(i.__class__)  # -> Int
print(type(type(i)))  # -> type
print(i)  # -> -1

j = Int(1)
print(j)  # -> 1
Run Code Online (Sandbox Code Playgroud)

要真正深入了解工作原理type,请查看. 您可以看到(向下滚动几行)这是一种特殊情况,它立即返回 的类型(又称类)。当您执行此操作时,将调用类型创建机制。type_newtype(x)xtype(name, bases, dict)

为了获得更多乐趣,请尝试以下操作:

type(object)
type(type)
isinstance(object, object)
isinstance(type, object)
type(1)
type(type(1))
Run Code Online (Sandbox Code Playgroud)