今天,我发现不带__mro_entries__
的python对象可以用作基类
例如:
class Base:
def __init__(self, *args):
self.args = args
def __repr__(self):
return f'{type(self).__name__}(*{self.args!r})'
class Delivered(Base):
pass
b = Base()
d = Delivered()
class Foo(b, d):
pass
print(type(Foo) is Delivered)
print(Foo)
True
Delivered(*('Foo', (Base(*()), Delivered(*())), {'__module__': '__main__', '__qualname__': 'Foo'}))
因此Foo
将是Delivered
类的实例,并且它不是有效的类型
我确实理解__mro_entries__
的用例,但不使用__mro_entries__
作为基类的对象的用例是什么。这是python的一个bug吗
TL;DR不是一个bug,而是对
class
语句的极端滥用class
语句是equivalent to a call to a metaclass。由于缺少显式的metaclass
关键字参数,必须从基类推断元类。这里,“类”b
的“元类”是Base
,而d
的元类是Delivered
。由于每个都是公共元类(Base
)的非严格子类,因此选择Delivered
作为更具体的元类Delivered
可以用作元类,因为它接受与class
语句期望元类接受的参数相同的参数:类型名称的字符串、父类序列和用作命名空间的映射。在这种情况下,Delivered
不使用它们来创建类型;它只是打印参数因此,
Foo
被绑定到Delivered
的实例,而不是类型。因此Foo
是一个类,仅在它是由class
语句生成的意义上:它显然是而不是类型相关问题 更多 >
编程相关推荐