Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Decorator

Back


Function as Object


Decorator

print("\n--------Example: without decorator--------\n")


# def divide(x, y):
#     print(x/y)


def outer_div(func):
    '''high order function'''
    def inner(x, y):
        if (x < y):
            x, y = y, x
        return func(x, y)
    return inner


# divide1 = outer_div(divide)
# divide1(2, 4)   # 2.0

print("\n--------Example: without decorator--------\n")


def outer_div(func):
    '''high order function'''
    def inner(x, y):
        if (x < y):
            x, y = y, x
        return func(x, y)
    return inner
# syntax of generator


@outer_div
def divide(x, y):
    '''
    Using decorator to define this function
    will be passed to outer_div function as
    an argument
    '''
    print(x/y)


divide(2, 4)    # 2.0, call function directly


Reuse decorator

def do_twice(func):
    def wrapper_function(*args, **kwargs):
      #using abritary parameter to accept unkown number of arguments
      func(*args, **kwargs)
      func(*args, **kwargs)
    return wrapper_function

from mod_decorator import do_twice
print("\n--------Reuse decorator--------\n")


@do_twice
def display(name):
    print(f"Hello {name}")


display("John")
# Hello John
# Hello John

Class Decorators

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    @staticmethod
    def hello():
        print("Hello Peter")

    @property
    def display(self):
        return self.name + " got grade " + self.grade


stu = Student("John", "B")
print("Name:", stu.name)        # Name: John
print("Grade:", stu.grade)      # Grade: B

# @property
print(stu.display)              # John got grade B

# @staticmethod
stu.hello()                     # Hello Peter
Student.hello()                 # Hello Peter

Nesting Decorators

print("\n--------Nested Decorator--------\n")


def function1(func):
    def inner_func(*args, **kwargs):
        print("function1")
        func(*args, **kwargs)
        func(*args, **kwargs)
        print("------")
    return inner_func


def function2(func):
    def inner_func(*args, **kwargs):
        print("     function2")
        func(*args, **kwargs)
        func(*args, **kwargs)
        func(*args, **kwargs)
        print("     ------")
    return inner_func


@function1
@function2
def function(name):
    print(f"{name}")


function("John")
# function1
#      function2
# John
# John
# John
#      ------
#      function2
# John
# John
# John
#      ------
# ------

更多在 functools 中


TOP