lundi 20 juin 2016

Python inheritance, method overloading, and decorating

I have a class B that inherits from A :

class A():
    def do_something(self, x):
        """Prints x."""
        print(x)

class B(A):
    def something_else(self, x):
        print("This isn't the same.")

I'd like to achieve a few things :

  • I'd like for B.do_something to inherit the docstring from A.do_something. I think functools.wraps is the recommended solution : is that right ?
  • Let's say there are some methods of A that return an instance of A. If I call those methods from B, I'd like them to return an instance of B. So far, I'm overloading each function manually.

    def method_of_A(self, *args, **kwargs):
        return A(super(self.__class__, self).method_of_A(*args, **kwargs))
    

    There's likely a better way - especially given that I have to do this for a large number of classes. Is there same way to check if a function is defined within B and, if not but available in A, have it decorated / wrapped to return an instance of B ? EDIT : I can't make changes to A's codebase.

  • Are there solutions that are Py2 and Py3 compatible ?

Thanks very much for any suggestions.

Aucun commentaire:

Enregistrer un commentaire