Example of using the modifier in Python Programming

Source: Internet
Author: User

Example of using the modifier in Python Programming

Decoration functions and methods

We first define two simple mathematical functions, one for calculating the sum of squares and the other for calculating the square difference:

# get square sumdef square_sum(a, b):  return a**2 + b**2# get square diffdef square_diff(a, b):  return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

After having basic mathematical functions, we may want to add other functions for functions, such as printing input. We can rewrite the function to achieve this:

# modify: print input# get square sumdef square_sum(a, b):  print("intput:", a, b)  return a**2 + b**2# get square diffdef square_diff(a, b):  print("input", a, b)  return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

We modified the function definition and added the function.

Now, we use the decorator to implement the above modification:

def decorator(F):  def new_F(a, b):    print("input", a, b)    return F(a, b)  return new_F# get square sum@decoratordef square_sum(a, b):  return a**2 + b**2# get square diff@decoratordef square_diff(a, b):  return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

Decorator can be defined in the format of def, such as decorator in the code above. The decorator receives a callable object as the input parameter and returns a new callable object. The modifier creates a new callable object, namely the new_F above. In new_F, the printing function is added and the original function is implemented by calling F (a, B.

After the decorator is defined, we can use the @ syntax. Call @ decorator before the square_sum and square_diff functions are defined. We actually pass square_sum or square_diff to decorator, and assign the new callable object returned by decorator to the original function name (square_sum or square_diff ). Therefore, when we call square_sum (3, 4), it is equivalent:

square_sum = decorator(square_sum)square_sum(3, 4)

We know that the variable names and objects in Python are separated. The variable name can point to any object. In essence, the modifier acts as a name binding to redirect the same variable name to a new callable object, this allows you to modify callable objects.

Similar to the processing function, we can use the decoration machine processing method.

If we have other similar functions, we can continue to call the decorator to modify the function, instead of repeatedly modifying the function or adding new encapsulation. In this way, we have improved the reusability of the program and increased the readability of the program.

Parameter-included decorators

In the above decorator call, for example @ decorator, the function next to the decorator is a unique parameter by default. The decorator syntax allows us to provide other parameters when calling decorator, such as @ decorator (). In this way, it provides more flexibility for writing and using the decorator.

# a new wrapper layerdef pre_str(pre=''):  # old decorator  def decorator(F):    def new_F(a, b):      print(pre + "input", a, b)      return F(a, b)    return new_F  return decorator# get square sum@pre_str('^_^')def square_sum(a, b):  return a**2 + b**2# get square diff@pre_str('T_T')def square_diff(a, b):  return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))

The pre_str above is a modifier that allows parameters. It is actually a function encapsulation of the original decorator and returns a decorator. We can understand it as a closure containing environment parameters. When we call it using @ pre_str ('prop _^ '), Python can discover the encapsulation of this layer and pass the parameters to the decorator environment. This call is equivalent:

square_sum = pre_str('^_^') (square_sum)

Decoration

In the preceding example, the modifier receives a function and returns a function to process the function. After Python 2.6, the decorator is extended to the class. A decorator can receive a class and return a class to achieve the processing effect.

def decorator(aClass):  class newClass:    def __init__(self, age):      self.total_display  = 0      self.wrapped     = aClass(age)    def display(self):      self.total_display += 1      print("total display", self.total_display)      self.wrapped.display()  return newClass@decoratorclass Bird:  def __init__(self, age):    self.age = age  def display(self):    print("My age is",self.age)eagleLord = Bird(5)for i in range(3):  eagleLord.display()

In decorator, we return a new class newClass. In the new class, we record the object (self. wrapped) generated by the original class and append the new attribute total_display to record the number of times display is called. We also changed the display method.

Through modification, our Bird class can display the number of times display is called.

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.