Python advanced tutorial function object (function is also an object), python advanced tutorial

Source: Internet
Author: User

Python advanced tutorial function object (function is also an object), python advanced tutorial

Adhering to the idea that everything is an object, let's look back at functions again ). A function is also an object with attributes (which can be queried using dir ). As an object, it can also be assigned to other object names or passed as a parameter.

Lambda Functions

Before expanding, we should first mention the lambda function. You can use the syntax of the lambda function to define the function. Lambda example:
Copy codeThe Code is as follows:
Func = lambda x, y: x + y
Print func (3, 4)

Lambda generates a function object. The return value is x + y. Function objects are assigned to func. The call of func is no different from that of a normal function.

The preceding definition can be written as follows:
Copy codeThe Code is as follows:
Def func (x, y ):
Return x + y

Passing functions as parameters

A function can be used as an object to transmit parameters. Function Name (such as func) is the object. For example:
Copy codeThe Code is as follows:
Def test (f, a, B ):
Print 'test'
Print f (a, B)

Test (func, 3, 5)

The first parameter f of the test function is a function object. Pass func to f. f () in test has the func () function.

Therefore, we can improve program flexibility. You can use the test function above to bring different function parameters. For example:
Copy codeThe Code is as follows:
Test (lambda x, y: x ** 2 + y), 6, 9)

Map () function

Map () is a built-in function of Python. Its first parameter is a function object.
Copy codeThe Code is as follows:
Re = map (lambda x: x + 3), [1, 3, 5, 6])

Here, map () has two parameters: a function object defined by lambda and a table containing multiple elements. Map () is used to act on each element of a table in sequence, and the results of each function are stored in the returned table re. Map uses the READ function (lambda function) to operate data (here "data" is each element in the table, and "operation" is to add 3 to each data ).

In Python 3. X, the returned value of map () is a circular object. You can use the list () function to convert the circular object into a table.

If the function object as a parameter has multiple parameters, you can use the following method to pass multiple parameters of the function parameter to map:
Copy codeThe Code is as follows:
Re = map (lambda x, y: x + y), [1, 2, 3], [6, 7, 9])

Map () extracts one element from two tables each time and brings it into the function defined by lambda.

Filter () function

The first parameter of the filter function is also a function object. It also acts on multiple elements as function objects of parameters. If the return value of the function object is True, the element is stored in the returned table. Filter filters data by reading functions. Similarly, in Python 3. X, filters return loop objects instead of tables.

The filter function is used as follows:

Copy codeThe Code is as follows:
Def func ():
If a> 100:
Return True
Else:
Return False

Print filter (func, [101,500,])

Reduce () function

The first parameter of the reduce function is also a function, but there is a requirement that the function itself can receive two parameters. Reduce can repeatedly act on each parameter. For example:
Copy codeThe Code is as follows:
Print reduce (lambda x, y: x + y), [1, 2, 5, 7, 9])

The first parameter of reduce is the lambda function, which receives two parameters x, y and returns x + y.

Reduce transfers the first two elements (1 and 2) of the table to the lambda function. 3 is displayed. The returned value (3) is used as the first parameter of the lambda function, and the next element (5) in the table is used as the second parameter of the lambda function, get 8. Call the lambda function in sequence. The first parameter of each lambda function is the result of the previous operation, and the second parameter is the next element in the table until there is no remaining element in the table.

The above example is equivalent to (1 + 2) + 5) + 7) + 9

According to mmufhy's reminder, the reduce () function cannot be used directly in 3.0. It is defined in the functools package and needs to be introduced. See the comment area.

Summary

A function is an object.

Define functions using lambda

Map ()

Filter ()

Reduce ()


What are Python classes, methods, objects, and instances? The concepts of methods, objects, and instances are rather vague,

Class is a set of functions. In this set, you define many functions. methods are actually the functions you define. In the following example, Class Plus is a Class. The two functions nested in this Class are called methods, but _ init _ is only used to initialize this Class, so it is not a method. The get_result function is a method.
For example:
Class Plus:
Def _ init _ (self, a, B)
Self. a =
Self. B = B
Def get_result (self)
Return self. a + self. B
In the above example, self is an object, which has two parameters: self. a. The other is self. b. The object is simply a variable with multiple attributes (or sub-variables. If the object is a general object, the instance is a specific object. The object is just a template with some attributes, and the instance is to fill in the data in this template. For example, if you write c1 = Plus (), c1 is an instance, and you can add c2 = Plus (), c2 is also an instance, however, they share common attributes and templates. The following example calls the method in the class:
Result1 = c1.get _ result () >>> 3. The output result is 3.
Result2 = c2.get _ result () >>> 5. The output result is 5.

How do I use the delete function in python? It is best to include an example,

I want to correct the statement in the recommendation answer!
Del is not used to delete the memory space pointed to by reference. del in python and delete in c ++ are completely two concepts ..

In general, del is used to delete the reference of a variable, for example, a = 1; del a. Here a is a reference to the value of 1 (all variables in python can be considered as references ), del a deletes the reference relationship, that is, 1 is no longer referenced by the variable a, and the variable name a is also removed from the variable table.

If you still don't know, you will understand the following example:
A = object ()
B =
Del
Print B
Print a # This statement will report an undefined exception of.
In this Code, a references a new object (), and B = a makes B reference this object. Although a and B are two variables, however, they reference the same object, which is similar to the two pointers in c ++ pointing to the same object.
Del a only deletes the reference of the variable a to object (), and the variable name of a is invalid, but it does not mean that the object () is deleted, it is still there, and B still references it. This can be seen from the print B output below.

The memory release of python uses the reference counting mechanism, that is, when an object does not have any variables that reference it, it will be automatically released without manual intervention.

In addition, del has different functions for different objects, depending on the implementation of the _ del _ System Method of the object itself. For example, if List a = [1, 2, 3], del a [0] indicates that the first item of the List is deleted, and then a is changed to [2, 3. If it is a custom object, the del function can be defined as anything you want. For details, see the _ del _ entry in the python help.

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.