Cooperative methods and superGuido在python中實現Super時出現了什麼問題?
這是一個例子純Python實現的內置super
由Guido用於說明目的。我需要在類別Super
下執行一些說明
在下面的代碼調用someobj.__mro__
將不起作用。看到我的評論反對該行。 隨着內置super
只是一個錯誤拋出。
TypeError: super(type, obj): obj must be an instance or subtype of type
問:
我的問題是什麼是有擺在首位該行的意圖是什麼?
因此,如果傳入的對象不是傳入的類中的實例,那麼請使用該對象的mro ...爲什麼?
class Super(object):
def __init__(self, type, obj=None):
self.__type__ = type
self.__obj__ = obj
def __get__(self, obj, type=None):
if self.__obj__ is None and obj is not None:
return Super(self.__type__, obj)
else:
return self
def __getattr__(self, attr):
if isinstance(self.__obj__, self.__type__):
starttype = self.__obj__.__class__
else:
starttype = self.__obj__ ## This line does not work
mro = iter(starttype.__mro__)
for cls in mro:
if cls is self.__type__:
break
# Note: mro is an iterator, so the second loop
# picks up where the first one left off!
for cls in mro:
if attr in cls.__dict__:
x = cls.__dict__[attr]
if hasattr(x, "__get__"):
x = x.__get__(self.__obj__)
return x
raise AttributeError, attr
class A(object):
def m(self):
''' m in A'''
return "A"
class B(A):
def m(self):
''' m in B'''
return "B" + Super(B, self).m()
class C(A):
def m(self):
''' m in C '''
return "C" + Super(C, self).m()
class D(C):
def m(self):
''' m in D'''
return "D" + Super(B, self).m()
print D().m() # "DCBA"
堆棧跟蹤:
Traceback (most recent call last):
File "./supertest.py", line 73, in <module>
print D().m() # "DCBA"
File "./supertest.py", line 71, in m
return "D" + Super(B, self).m()
File "./supertest.py", line 33, in __getattr__
mro = iter(starttype.__mro__)
AttributeError: 'D' object has no attribute '__mro__'
發佈整個堆棧跟蹤。 – Marcin