问题
How do I fill in the ???
?
def ensure_finished(iterator):
try:
next(iterator)
except StopIteration:
return
else:
raise RuntimeError
def derived_generator(method):
def new_method(self, *args, **kwargs):
x = method(self, *args, **kwargs)
y = getattr(super(???, self), method.__name__)\
(*args, **kwargs)
for a, b in zip(x, y):
assert a is None and b is None
yield
ensure_finished(x)
ensure_finished(y)
return new_method
回答1:
EDIT : This does not work for the reasons mentioned in the comments. I'll leave this here so that the next guy trying to answer doesn't do the same thing (until the real answer shows up).
You should use type(self)
Example I simplified your code a bit, but the essence should still be in there
def derived_generator(method):
def new_method(self, *args, **kwargs):
x = method(self, *args, **kwargs)
y = getattr(super(type(self), self), method.__name__)\
(*args, **kwargs)
for a, b in zip(y, x):
yield a, b
return new_method
class BaseClass(object):
def iterator(self):
return [1, 2, 3]
class ChildClass(BaseClass):
@derived_generator
def iterator(self):
return [4, 5, 6]
a = ChildClass()
for x in a.iterator():
print(x)
来源:https://stackoverflow.com/questions/25921537/how-do-i-call-super-in-a-method-decorator-in-python-3