Search code examples
pythondecoratorpython-decorators

Can anyone explain, why the result was 400 instead of 200?


#source : https://www.geeksforgeeks.org/decorators-in-python/ #Python Decorators

def decor1(func):
    def inner():
        x = func()
        return x * x
    return inner

def decor(func):
    def inner():
        x = func()
        return 2 * x
    return inner

@decor1
@decor
def num():
    return 10

print(num())

Solution

  • It's an expected result,

    decor1(decor(num())) # it's call like this.
    
    decor >> return 10 *2 >> 20
    
    decor1 >> return 20 * 20 >> 400
    

    And I would suggest putting the print inside the decorator to identify the execution order.

    <function decor at 0x113de8430>
    10
    <function decor1 at 0x113bfc430>
    20
    400