functools.wraps equivalent for class decorator

后端 未结 2 1010
[愿得一人]
[愿得一人] 2021-02-14 07:16

When we decorate function, we use functools.wraps to make decorated function look like original.

Is there any wat to do same, when we want to decorate class?

<         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-14 08:07

    Oh, I guess now I understand what are your trying to achieve.

    You want to attach new methods from a "wrapper" using a class decorator.

    Here is a workng example:

    class Wrapper(object):
        """Some Wrapper not important doc."""
        def another_method(self):
            """Another method."""
            print 'Another method'
    
    
    def some_class_decorator(cls_to_decorate):
        return type(cls_to_decorate.__name__, cls_to_decorate.__bases__, dict
            (cls_to_decorate.__dict__, another_method=Wrapper.__dict__['another_method']))
    
    
    class MainClass(object):
        """MainClass important doc."""
        def method(self):
            """A method."""
            print "A method"
    
    
    help(MainClass)
    _MainClass = some_class_decorator(MainClass)
    help(_MainClass)
    _MainClass().another_method()
    MainClass().another_method()
    

    This example creates a new class not modifying the old class.

    But I guess you could also just inject the given methods in the old class, modifying it in place.

提交回复
热议问题