Python Basic Learning Note 3

Source: Internet
Author: User
Tags mathematical functions

Special methods and multi-paradigm

Python is all object, but at the same time, Python is a multi-paradigm language (MULTI-PARADIGM), you can not only use object-oriented way to write programs, but also in a process-oriented way to write the same function of the program (there are functions, declarative, etc., we do not drill down). Python's multi-paradigm relies on special methods in Python objects (special method).

The special method name has two underscores before and after each. Special methods are also used as magic methods, which define many of the Python syntax and expressions, as we will see in the following example. Python also has "special privileges" when it defines special methods in the object. For example, a class that defines the __init__ () method automatically executes the action in the __init__ () method when the object is created.

For built-in objects (such as integers, tables, strings, and so on), the special methods they need are already ready in Python. User-defined objects can also implement custom syntax by adding special methods. Special methods are closer to the bottom of Python, and many of the implementations of Python functionality depend on special methods. Context Manager Context Manager, which is Python2.5, starts supporting a medium syntax used to specify the scope of use of an object. Once you enter or leave the scope of use, special actions are invoked (such as allocating or freeing memory for an object). Its grammatical form is with...as ... Close FileWe will do this: Open the file, read and write, close the file. Programmers often forget to close files. The context Manager can automatically close files when no files are needed. Let's take a look at two programs:
# without context managerF = open ("new.txt""w")  Print(f.closed)               #  Whether the file is openf.write ("Hello world! " ) f.close ()print(f.closed)

And:

 #   with the context manager  with open ( Span style= "color: #800000;" > " new.txt  " ,  " w  "   print   (f.closed) F.write ( Span style= "color: #800000;" > " hello world!   " )  print  (f.closed) 
The two programs actually perform the same operation. Our second program uses the context Manager (With...as ...). The context manager has a program block that belongs to it. The context Manager automatically closes the file (we can query whether the file is closed by f.closed) when the subordinate block execution is finished (that is, no longer indented). It is equivalent to using indentation to specify the scope of use of the file object F. The context manager above is based on the __exit__ () special method of the F object (remember how we use special methods to implement various syntaxes?). See special methods and multiple paradigms). When we use the syntax of the context manager, we actually ask Python to call the __enter__ () method of the object before it enters the block, and call the __exit__ () method when the block is closed. For file object F, it defines the __enter__ () and __exit__ () methods (which can be seen through Dir (f)). In the __exit__ () method of F, there is a self.close () statement. So when using the context manager, we don't have to close the F file in plaintext. Custom:Any object that defines the __enter__ () and __exit__ () methods can be used in the context manager. The file object F is a built-in object, so F automatically comes with these two special methods and does not require customization. properties of the object Python is all objects (object), and each object may have multiple properties (attribute). The properties of Python have a unified management scheme.

The properties of an object may come from its class definition, called Class attribute. Class properties may come from the class definition itself, or it may be inherited from a class definition. The properties of an object may also be defined by the object instance, called the object attribute.

The properties of the object are stored in the __dict__ property of the object. __dict__ is a dictionary, the key is the property name, and the corresponding value is the property itself. Closed Package Closure (closure) is an important grammatical structure of functional programming. Functional programming is a programming paradigm (both procedural programming and object-oriented programming are also programming paradigms). In process-oriented programming, we have seen functions (function), and in object-oriented programming we have seen objects (object). The fundamental purpose of functions and objects is to organize the code in some logical way and to improve the code's repeatability (reusability). Closures are also a structure for organizing code, which also improves the reusable nature of code. A function is an object that can be returned as a result of a function:
def line_conf ():     def Line (x):         return 2*x+1    return line          #  return a Function object= line_conf () Print (My_line (5))
The above code can run successfully. The return result of the line_conf is assigned to the line object. The above code will print 11. What happens if the external variables are referenced in the definition of line ()?
def line_conf ():     =    def line  (x):        return 2*x+b    return line            #  return a function objectb = 5= line_conf ()print(My_line (5))

As we can see, the line definition of the subordinate program block refers to the high-level variable B, but B information exists outside the definition of line (b is not defined in the line's membership block). We call b the environment variable for line. In fact, when line is the return value of line_conf, the value of B is included in line (although B is not affiliated with line).

The above code will print 25, which means that the B value referenced by line is the B value that is available for reference when the function object is defined, rather than the B value when used. Let's look at a practical example of a closure:
def line_conf (A, B):     def Line (x):         return ax + b    return= line_conf (1, 1= line_conf (4, 5) Print (Line1 (5), line2 (5))
In this example, the function line and the environment variable A, a and B constitute the closure. When we created the closure, we explained the values of the two environment variables through the line_conf parameter, a and B, so that we determined the final form of the function (y = x + 1 and y = 4x + 5). We only need to change the parameter, a, B, we can get a different line expression function. Thus, we can see that closures also have the effect of improving code reusability. Without closures, we need to explain a,b,x each time we create a line function. In this way, we need more parameter passing and less portability of the code. With closures, we actually created the functional. The line function defines a broad-sense function. Some aspects of this function have been determined (must be straight lines), but others (such as the A and B parameters are pending). We then determine the final function in the form of a closure, based on the parameters passed by line_conf. Decorative Device Let's first define two simple mathematical functions, one to calculate the sum of squares and one to calculate the squared difference:
# get square sumdef square_sum (A, B):    return a**2 + b**2#  get square diffdef Square_diff (A, B):    return a**2-b**2
Print (Square_sum (3, 4))
Print (Square_diff (3, 4))
After having basic mathematical functions, we may want to add other functions to the function, 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)returnA**2 + b**2#get square diffdef Square_diff (A, b):    Print("input", A, b)returnA**2-b**2Print(Square_sum (3, 4))Print(Square_diff (3, 4))

We have modified the definition of the function to add functionality to the function. Now, we use adorners to implement the above modifications:
defDecorator (F):defNew_f (A, b):Print("input", A, b)returnF (A, b)returnNew_f#get square [email protected]defSquare_sum (A, b):returnA**2 + b**2#get square [email protected]defSquare_diff (A, b):returnA**2-b**2Print(Square_sum (3, 4))Print(Square_diff (3, 4))

Adorners can be defined in the form of Def, such as decorator in the code above. The adorner receives a callable object as an input parameter and returns a new callable object. The adorner creates a new callable object, which is the new_f above. In New_f, we added the function of printing and realized the function of the original function by calling F (A, B).

Once we've defined the adorner, we can use the @ syntax. Call @decorator before the function square_sum and Square_diff are defined, we actually pass square_sum or Square_diff to decorator, and assigns the new callable object returned by decorator to the original function name (Square_sum or Square_diff). So, when we call Square_sum (3, 4), it's equivalent to: Square_sum = Decorator (square_sum) square_sum (3, 4)

We know that the variable names and objects in Python are separate. A variable name can point to any object. In essence, the adorner plays the role of re-pointing to the variable name (name binding), so that the same variable name points to a newly returned callable object, thus achieving the purpose of modifying the callable object.

Similar to the machining function, we can use the adorner to process the class method. If we have other similar functions, we can continue to call decorator to modify the function without repeating the function or adding a new package. In this way, we improve the reusable nature of the program and increase the readability of the program. Summary Summarize
    • Context Manager
      • Automatically close files when no files are needed
      • With...as ...
        • has a block that belongs to it
        • Automatically close files when the block ends
    • Object Properties
    • Closed Package
      • The function line, and the environment variable, a and B, make up the closure and improve the reusability of the code.
    • Decorative Device
      • Improved reuse of programs and increased readability of programs

Python Basic Learning Note 3

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.