Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Chaining decorators result is confusing me

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())

Can someone explain why the result is 400?
Is it because inner is being returned twice?
I’m learning chaining decorators but it’s a bit confusing at first glance.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The num function returns 10, which is then passed to decor (one level higher) in variable x (note that func() refers to num(), hence it returns 10). x is multiplied by 2, yielding 20. The 20 is passed to decor1 (another level higher) in variable x and is multiplied by itself, so 20 times 20 yields 400.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading