如何在python初始化期间实现类方法

时间:2018-08-06 14:25:32

标签: python

让我们说我们要实现一个类接口,以相同的逻辑重载所有公共方法。因此,与其手动定义所有方法并在所有实现的方法之间复制粘贴逻辑,不如将过程抽象如下:

class Interface:
    def cat(self, i):
        """Implement."""

    def dog(self, i, j=2):
        """Implement."""


class Implementation(Interface):
    def __init__(self):
        for method in [method for method in vars(Interface) if '__' not in method]:
            setattr(self, method, lambda *a, **k: self.overload(method, *a, **k))

    def overload(self, method, *a, **k):
        print('Calling method {}'.format(method))
        return getattr(Interface, method)(self, *a, **k)


implementation = Implementation()
implementation.dog(1)
implementation.cat(1)
implementation.cat
implementation.dog

# Console:
# Calling method dog
# Calling method dog
# <function __main__.Implementation.__init__.<locals>.<lambda>(*a, **k)>
# <function __main__.Implementation.__init__.<locals>.<lambda>(*a, **k)>

一种解决方案可能是将__init__替换为以下内容,但随后的逻辑将无法完全抽象。

class Implementation(Interface):
    def __init__(self):
        setattr(self, 'cat', lambda *a, **k: self.overload('cat', *a, **k))
        setattr(self, 'dog', lambda *a, **k: self.overload('dog', *a, **k))

    def overload(self, method, *a, **k):
        print('Calling method {}'.format(method))
        return getattr(Interface, method)(self, *a, **k)

implementation = Implementation()
implementation.dog(1)
implementation.cat(1)

# Console.
# Calling method dog
# Calling method cat

问题:如何在初始化Interface的过程中重写Implementation的所有公共方法?

0 个答案:

没有答案