Python uses the decorator for computing instance analysis

Source: Internet
Author: User
This article mainly uses the Python decorator for an example to introduce the Python decorator in detail. it is very practical. if you need it, you can refer to it. Today, I want to use the python decorator for an operation. the code is as follows:

>>> def mu(x):  def _mu(*args,**kwargs):    return x*x  return _mu>>> @mudef test(x,y):  print '%s,%s' %(x,y)>>> test(3,5)Traceback (most recent call last): File "
 
  ", line 1, in 
  
     test(3,5) File "
   
    ", line 3, in _mu  return x*xTypeError: unsupported operand type(s) for *: 'function' and 'function'
   
  
 

It turns out that functions and functions cannot be computed in this way!

What should we do?

In [1]: from functools import wrapsIn [2]: def mu(x):  ...:     @wraps(x)  ...:     def _mu(*args,**kwargs):  ...:             x,y=args  ...:             return x*x  ...:     return _mu  ...: In [3]: @mu  ...: def test(x,y):  ...:     print '%s,%s' %(x,y)  ...:   In [4]: test(3,4)Out[4]: 9

When implementing the Python decorator, you need to pay attention to some details. For example, the decorated function is actually another function (function attributes such as the function name will change)

The Python functools package provides a decorator called wraps to eliminate such side effects. When writing a decorator, it is best to add the functools wrap before implementation, which can retain the name of the original function and docstring.

The above is all the content of this article. I hope you will like it.

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.