zoukankan      html  css  js  c++  java
  • Python Decorators

    It is a way to run extra processing steps at function and class definition time with explicit syntax. It comes in two flavors:

    • Function decorators—the initial entry in this set. They specify special operation modes for both simple functions and clesses’s methods by wrapping them in an extra layer of logic implemented as another function, usually called metafunction.
    • Class decorators—a later extension. They do the same for classes, adding support for management of whole objects and their interfaces. Though perhaps simpler, they often overlap in roles with metaclasses.

    A First Look at User-Defined Function Decorators

    >>> class Tracer(object):
    	def __init__(self, func):
    		self.counter = 0
    		self.func = func
    	def __call__(self, *args,**kwargs):
    		self.counter += 1
    		print("call func:%s times:%d" % (self.func.__name__, self.counter))
    		return self.func(*args, **kwargs)
    
    	
    >>> @Tracer
    def add(x, y):
    	return x + y
    
    >>> add(1, 1)
    call func:add times:1
    2
    >>> add(2, 2)
    call func:add times:2
    4
    >>> 
  • 相关阅读:
    C语言I博客作业09
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言II博客作业04
    C语言II博客作业03
    C语言II博客作业02
    C语言|博客作业01
    学期总结
  • 原文地址:https://www.cnblogs.com/hotbaby/p/4917596.html
Copyright © 2011-2022 走看看