zoukankan      html  css  js  c++  java
  • Decorator

    A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.

    Decorator修饰符,可以方便地对函数和类进行_修饰_。

    Function decorators

    def decorator_function(original_function):
    	def wrapper_function(*args, **kwargs):
    		print('Wrapper executed this before!')
    		return original_function(*args, **kwargs)
    	return wrapper_function
    
    @decorator_function # display = decorator_function(display)
    def display():
    	print('display function ran')
    
    @decorator_function
    def display_info(name, age):
    	print('display_info ran with arguments ({}, {})'.format(name, age))
    
    # display_info('John', 25)
    # display()
    

    Class decorators

    class decorator_class(object):
    	def __init__(self, original_function):
    		self.original_function = original_function
    
    	def __call__(self, *args, **kwargs):
    		print('Call method executed this before!')
    		return self.original_function(*args, **kwargs)
    
    @decorator_class # display = decorator_function(display)
    def display():
    	print('display function ran')
    
    @decorator_class
    def display_info(name, age):
    	print('display_info ran with arguments ({}, {})'.format(name, age))
    
    display_info('John', 25)
    display()
    
  • 相关阅读:
    windows 7 codepage id name 名称
    最大团
    三分的多种写法及对应的精度 三分套三分原理
    AC自动机
    c++ queue
    lca 欧拉序+rmq(st) 欧拉序+rmq(线段树) 离线dfs 倍增
    node *p,*q
    dfs序和欧拉序
    P3861 8月月赛A
    洛谷P3862 8月月赛B
  • 原文地址:https://www.cnblogs.com/yaos/p/14014354.html
Copyright © 2011-2022 走看看