def test_altmro(self):
# Testing mro() and overriding it...
class A(object):
def f(self): return "A"
class B(A):
pass
class C(A):
def f(self): return "C"
class D(B, C):
pass
self.assertEqual(D.mro(), [D, B, C, A, object])
self.assertEqual(D.__mro__, (D, B, C, A, object))
self.assertEqual(D().f(), "C")
class PerverseMetaType(type):
def mro(cls):
L = type.mro(cls)
L.reverse()
return L
class X(D,B,C,A):
__metaclass__ = PerverseMetaType
self.assertEqual(X.__mro__, (object, A, C, B, D, X))
self.assertEqual(X().f(), "A")
try:
class X(object):
class __metaclass__(type):
def mro(self):
return [self, dict, object]
# In CPython, the class creation above already raises
# TypeError, as a protection against the fact that
# instances of X would segfault it. In other Python
# implementations it would be ok to let the class X
# be created, but instead get a clean TypeError on the
# __setitem__ below.
x = object.__new__(X)
x[5] = 6
except TypeError:
pass
else:
self.fail("devious mro() return not caught")
try:
class X(object):
class __metaclass__(type):
def mro(self):
return [1]
except TypeError:
pass
else:
self.fail("non-class mro() return not caught")
try:
class X(object):
class __metaclass__(type):
def mro(self):
return 1
except TypeError:
pass
else:
self.fail("non-sequence mro() return not caught")
评论列表
文章目录