Three ways to implement decorative patterns in Python

Source: Internet
Author: User
Tags wrapper

Directory (?) [+]

function target

Write an adorner that can print the decorated function name, execution time, memory address

Predecessor Dependency Package

Import time
Import Functools
From decorator import Decorator

Based on common function nesting
def log1(fn):     def _wrapper(*args, **kwargs): start = time.clock() result = fn(*args, **kwargs) print("%s is invoked with time consumed: %s seconds at address %s" % (fn.__name__, str(time.time() - start), id(fn))) return result return _wrapper
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
Based on @decorator
@decoratordef log(f, *args, **kwargs): start = time.time() result = f(*args, **kwargs) print("%s is invoked with time consumed: %s at address %s" % (f.__name__, str(time.time() - start), id(f))) return result
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
Using @functools
def log2(f):    @functools.wraps(f) def wrapper(*args, **kwargs): start = time.clock() result = f(*args, **kwargs) print("%s is invoked with time consumed: %s seconds at address %s" % (f.__name__, str(time.time() - start), id(f))) return result return wrapper
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
Test
@log2def f11(x, y): return x**yresult = f11(2,3)print("result:" + str(result))
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

Switching to a different implementation, their effect is the same.

http://www.woaipu.com/shops/zuzhuan/61406
Http://www.znds.com/tv-967956-1-1.html
Http://www.znds.com/tv-967958-1-1.html

Three ways to implement decorative patterns in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.