How do I extend a python module? Adding new functionality to the `python-twitter` package

后端 未结 6 1268
逝去的感伤
逝去的感伤 2020-11-28 09:53

What are the best practices for extending an existing Python module – in this case, I want to extend the python-twitter package by adding new methods to the bas

6条回答
  •  一个人的身影
    2020-11-28 10:45

    Define a new class, and instead of inherit it from the class you want to extend from the original module, add an instance of the original class as an attribute to your new class. And here comes the trick: intercept all non-existing method calls on your new class and try to call it on the instance of the old class. In your NewClass just define new or overridden methods as you like:

    import originalmodule
    
    class NewClass:
        def __init__(self, *args, **kwargs):
            self.old_class_instance = originalmodule.create_oldclass_instance(*args, **kwargs)
    
        def __getattr__(self, methodname):
            """This is a wrapper for the original OldClass class.
    
            If the called method is not part of this NewClass class,
            the call will be intercepted and replaced by the method
            in the original OldClass instance.
            """
            def wrapper(*args, **kwargs):
                return getattr(self.old_class_instance, methodname)(*args, **kwargs)
            return wrapper
    
        def new_method(self, arg1):
            """Does stuff with the OldClass instance"""
            thing = self.old_class_instance.get_somelist(arg1)
            # returns the first element only
            return thing[0]
    
        def overridden_method(self):
            """Overrides an existing method, if OldClass has a method with the same name"""
            print("This message is coming from the NewClass and not from the OldClass")
    

    In my case I used this solution when simple inheritance from the old class was not possible, because an instance had to be created not by its constructor, but with an init script from an other class/module. (It is the originalmodule.create_oldclass_instance in the example above.)

提交回复
热议问题