2

I have a scenario where I can accept different objects (classes or functions) and I wrap them with a class to enhance their capabilities and I want to still be able to access their native methods (that I didn't write).

With the __call__ function, I can easily pass the arguments to the native __call__ function, but how can I still route the functions I don't know beforehand to their native functions?

For example:

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)   # <--------------

In this example, the last one will fail, because native_method does not exist in the Wrapper class, but it exists in the class_a original structure.

How can I support the native functionality while adding my own? Am I taking the wrong approach? Is there a better way to do it? Is it even possible?

bluesummers
  • 11,365
  • 8
  • 72
  • 108
  • This should also be tagged with [tag:python]... – user202729 Aug 21 '18 at 10:17
  • Possible duplicate of [How to copy all properties of an object to another object, in Python?](https://stackoverflow.com/questions/243836/how-to-copy-all-properties-of-an-object-to-another-object-in-python) – user202729 Aug 21 '18 at 10:22
  • so in this code it just so happens that `class_a` has a `__call__` function? – AntiMatterDynamite Aug 21 '18 at 10:42
  • does it have to be literally the same `Wrapper` class? usually do modify behavior you inherit from a class, you can just create two wrappers one for functions and one for a class – AntiMatterDynamite Aug 21 '18 at 10:44
  • Yep, it just so happens that it has a `__call__` function. I get what you are saying. I'm open for a split solution - but I can't tell from which class the classes will inherit – bluesummers Aug 21 '18 at 10:47

0 Answers0