type 被称为“元类”,因为它是产生其他类(AKA 类型)的类。它的行为就像一个普通的类。特别是,它相当于 __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
请注意,当实例化一个类时,新实例的值是从__new__ 返回的值。对于type,__new__ 总是返回一个类型对象(AKA 类)。下面是一个扩展 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
要真正深入了解type 的工作原理,请查看the C code in type_new。你可以看到(向下滚动几行)type(x) 是一个特例,它立即返回x 的类型(AKA 类)。当您执行type(name, bases, dict) 时,将调用类型创建机制。
如需更多乐趣,请尝试以下方法:
type(object)
type(type)
isinstance(object, object)
isinstance(type, object)
type(1)
type(type(1))