一个自己的类子类。为什么禁止相互子类化? [英] A class subclass of itself. Why mutual subclassing is forbidden?
问题描述
复杂的问题我假设,但研究OWL打开了一个新的视角,生活,宇宙和一切。
Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here.
我想实现一个C类,它是B的子类,它又是C的子类。只是为了有趣,你知道。 ..
I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know...
这里是
>>> class A(object): pass
...
>>> class B(A): pass
...
>>> class C(B): pass
...
>>> B.__bases__
(<class '__main__.A'>,)
>>> B.__bases__ = (C,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a __bases__ item causes an inheritance cycle
>>>
很清楚,python是聪明的,禁止这。然而,在OWL中,可以将两个类定义为相互子类。问题是:为什么在OWL(这不是一种编程语言)中允许使用并且不允许在编程语言中使用?为什么这个问题是令人费解的?
clearly, python is smart and forbids this. However, in OWL it is possible to define two classes to be mutual subclasses. The question is: what is the mind boggling explanation why this is allowed in OWL (which is not a programming language) and disallowed in programming languages ?
推荐答案
Python不允许它,因为没有明智的方法来做到这一点。你可以发明关于如何处理这种情况的任意规则(也许有一些语言做),但是由于没有实际的收获,Python拒绝猜测。由于多种原因,类需要具有稳定,可预测的方法解析顺序,因此不允许出现奇怪,不可预测或令人惊讶的MRO。
Python doesn't allow it because there is no sensible way to do it. You could invent arbitrary rules about how to handle such a case (and perhaps some languages do), but since there is no actual gain in doing so, Python refuses to guess. Classes are required to have a stable, predictable method resolution order for a number of reasons, and so weird, unpredictable or surprising MROs are not allowed.
em>是在Python中的特殊情况: type
和 object
。 对象
是类型
的实例,类型
是 object
的子类。当然, type
也是 一个类型
的实例(因为它是 object
)。这可能是为什么OWL允许它:如果你想让一切都是一个对象,并且所有对象都有一个类,你需要以一个奇异的方式启动一个类/元类层次。
That said, there is a special case in Python: type
and object
. object
is an instance of type
, and type
is a subclass of object
. And of course, type
is also an instance of type
(since it's a subclass of object
). This might be why OWL allows it: you need to start a class/metaclass hierarchy in some singularity, if you want everything to be an object and all objects to have a class.
这篇关于一个自己的类子类。为什么禁止相互子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!