我需要一种从抽象方法调用函数的方法,即
class A(object):
@abc.abstractmethod
def method1(self):
raise Exception("Unimplemented method")
def method2(self):
print "method1 finished"
class B(A):
def method1(self):
print "executing method1 from class B"
我需要一种方法来在 method1
执行后自动调用类 A
的 method2
(应该在类上完成A
端 - 独立于继承的类)。
有什么好的方法吗?
最佳答案
您可以使用元类,它在创建类时包装 method1
:
from functools import wraps
class MetaA(type):
def __new__(meta, name, bases, attr):
method1 = attr['method1']
if not getattr(method, '__isabstractmethod__'):
@wraps(method1)
def wrapper(self, *args, **kw):
res = method1(self, *args, **kw)
self.method2()
return res
attr['method1'] = wrapper
return super(MetaA, meta).__new__(meta, name, bases, attr)
class A(object):
__metaclass__ = MetaA
@abc.abstractmethod
def method1(self):
raise Exception("Unimplemented method")
def method2(self):
print "method1 finished"
每当创建(子)类时,这基本上将装饰器应用于特定方法。
另一种方法,有点 hackish,是拦截方法访问,但会起作用。您将在添加包装器的 A
上实现 __getattribute__
Hook :
from functools import wraps
class A(object):
@abc.abstractmethod
def method1(self):
raise Exception("Unimplemented method")
def method2(self):
print "method1 finished"
def __getattribute__(self, name):
obj = super(A, self).__getattribute__(name)
if name == 'method1':
@wraps(obj)
def wrapper(*args, **kw):
res = obj()
self.method2()
return res
return wrapper
return obj
任何一种方法都会导致:
>>> B().method1()
executing method1 from class B
method1 finished
通过使用 @functools.wraps()
decorator包装器维护包装方法的几个重要属性,例如它的名称和文档字符串。
关于python - 为抽象函数指定退出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339527/