Decorators in Python


def greet(fx): # decorator function
    def mfx(*args, **kwargs):
        print("Welcome to this function!")
        fx(*args, **kwargs)
        print("Thanks for using this function.")
    return mfx

@greet
def add(a,b):
    print("The sum of your numbers is", a+b)

@greet
def thisWorld():
    print("This world is beautiful.")

# add(2,4)
# print()  # just to print a new line or blank line
# thisWorld()

# the above decorators can also be implemented in the following way...
greet(thisWorld())  # == greet(thisWorld)()
greet(add(3,4)) # == greet(add)(3,4)
    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes