The python decorator USES method instances

  • 2020-04-02 13:16:31
  • OfStack

What is a python decorator?

Definition on the web:
An decorator is a function that wraps a function, modifies an original function, reassures it to its original identifier, and permanently loses a reference to the original function.

The best examples of decorators are as follows:


#-*- coding: UTF-8 -*-
import time

def foo():
    print 'in foo()'

#  Define a timer, pass in one, and return another method with a timer attached 
def timeit(func):

    #  Defines an embedded wrapper function that wraps the incoming function with the timing function 
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start

    #  Returns the wrapped function 
    return wrapper

foo = timeit(foo)
foo()

Python provides a syntax sugar for the @ sign to simplify the above code, and they do the same thing


import time

def timeit(func):
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start
    return wrapper

@timeit
def foo():
    print 'in foo()'

foo()

These two pieces of code are the same. They're equivalent.

The built-in 3 decorator, they respectively are staticmethod, classmethod, property, their role is respectively the methods defined in the class into a static method, type of methods and properties are as follows:


class Rabbit(object):

    def __init__(self, name):
        self._name = name

    @staticmethod
    def newRabbit(name):
        return Rabbit(name)

    @classmethod
    def newRabbit2(cls):
        return Rabbit('')

    @property
    def name(self):
        return self._name

Nesting of decorators:
Just one rule: the nested order and the code order are reversed.
Here's another example:


#!/usr/bin/python
# -*- coding: utf-8 -*-
def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped
def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped
@makebold
@makeitalic
def hello():
    return "hello world"
print hello()

The result returned is:
< b > < i. > Hello world < / I > < / b >
Why this?
1. First, the hello function is decorated with the makeitalic function to become this result < i. > Hello world < / I >
2. This is then decorated with the makebold function to become < b > < i. > Hello world < / I > < / b > That's easy to understand.


Related articles: