Python-用类包装对象并保留其方法

时间:2018-08-21 10:10:40

标签: python-3.x

我有一个场景,我可以接受不同的对象(类或函数),并用一个类包装它们以增强其功能,并且我仍然希望能够访问其本机方法(我没有写过)。

借助__call__函数,我可以轻松地将参数传递给本地__call__函数,但是如何仍将事先不知道的函数传递给它们的本地函数呢?

例如:

import modules.i.didnt.write as some_classes
import modules.i.didnt.write2 as some_functions

class Wrapper:

    def __init__(self, module, attr_name):

        self.obj = getattr(module, attr_name)
        self.extra_args = ....


    def __call__(self, *args, **kwargs):
        return self.obj(*args, **kwargs)

    def added_functionality(self, ...):
        ....


wrapped_class = Wrapper(some_classes, 'class_a')
wrapped_function = Wrapper(some_functions, 'func_a')

wrapped_class(a=1, b=2)
wrapped_function(a=10, b=20)

wrapped_class.native_method(c=10)   # <--------------

在此示例中,最后一个将失败,因为native_method类中不存在Wrapper,而在class_a原始结构中存在。

添加自己的功能时如何支持本机功能? 我采用错误的方法吗?有更好的方法吗?甚至有可能吗?

0 个答案:

没有答案