How would one decorate an inherited method in the child class?

后端 未结 1 434
借酒劲吻你
借酒劲吻你 2021-02-13 16:59

I\'m not quite sure how to use a decorator on an inherited method. Normally decorators are put before the definition but for an inherited function the definition is given in the

1条回答
  •  一向
    一向 (楼主)
    2021-02-13 17:22

    You don't have to use a decorator in decorator syntax. It is just a callable:

    class Child(Person):
        def __init__(self, age):
            Person.__init__(self, age=age)
    
        gets_drink = dec(Person.gets_drink.__func__)
    

    This adds the return value of the decorator to the child class as a method with the same name. The __func__ attribute unwraps the bound (class) method, retrieving the original function.

    Note that your new method is now a regular method, not a classmethod, you'd have to re-wrap the result in a classmethod() call for that.

    This works because the syntax

    @decorator_expression
    def function_definition():
        pass
    

    is just syntactic sugar for:

    def function_definition():
        pass
    function_definition = decorator_expression(function_definition)
    

    0 讨论(0)
提交回复
热议问题