Decorator design: executing a method only if it has been overridden
I've stumbled in a tricky python question. Given (updated):
class A(object):
def run(self):
# This makes possible to determine if 'run' was overridden
if self.run.im_func != A.run.im_func:
print('Running in {0}'.format(self.__class__.__name__))
class B(A):
def run(self):
super(B, self).run()
class C(A):
pass
b = B()
c = C()
b.run()
>>> Running in B
c.run()
>>> # nothing :)
How would you design the @runoverriden decorator, that would do the job of conditional statement in A.run()?
Update: The purpose of this code is that A.run() should log the run() calls , only if it has been overridden.
Thank 开发者_Python百科you!
If I understand what you want:
import functools
def runoverridden(f):
@functools.wraps(f)
def wrapper(self, *args, **kw):
if getattr(self, f.__name__).im_func != wrapper:
return f(self, *args, **kw)
return wrapper
class A(object):
@runoverridden
def run(self):
print('Running in A')
class B(A):
def run(self):
super(B, self).run()
print('Running in B')
class C(A):
pass
b = B()
c = C()
b.run()
c.run()
It sounds like you want ABCs. Specifically, the abstractmethod decorator.
精彩评论