python - 为抽象函数指定退出函数

标签 python interface atexit

我需要一种从抽象方法调用函数的方法,即

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 执行后自动调用类 Amethod2(应该在类上完成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/

相关文章:

python - 如何在字典内的列表中查找值

c - atexit 被认为是有害的?

go - 接口(interface)的结构嵌入, panic : runtime error

python - 在注册的 atexit 函数中获取错误回溯

c++ - __cxa_atexit() 和 atexit() 有什么区别

python - Ruby 有哪些 Python 没有的,反之亦然?

python - Django:如何将用户与请求工厂相关联

python - pandas:内部函数的错误参数(在 iterators.c 中)

java - 将测试套件应用于接口(interface)的实现

C# 按实现拆分接口(interface)列表