Python section Fourth

Source: Internet
Author: User
Tags iterable variable scope

1.1Python function

Object oriented
Process oriented
1. Poor readability
2. Poor re-usability
Function-Type programming

1.1.1 Custom Functions

See an example of a function: DB file content is xuliangwei|123

def login (Username,password):
‘‘‘
For user Login
:p Aram Username: User Input user name
:p Aram Password: User input password
: Return:true, Login success false, Login failed
‘‘‘
file_name = open ("db", ' R ')
For line in file_name:
Line_list = Line.split ("|")
If line_list[0] = = Username and line_list[1] = = Password:
Return True
Return False
Explain:

1.DEF: keyword that represents a function
2. Function Name: The name of the function, and call the function according to the function name later
3. Function Body: A series of logical calculations in a function, such as: Sending mail
4. Return value: When the function is finished, you can return the data to the caller.
5. Parameters: Provide data for the function body (the Python function passes a parameter to pass a reference.) Instead of being re-assigned.)
1. General parameters (in strict order, the actual parameters are assigned to the formal parameters)
2. Default parameters (must be placed at the end of the parameter list)
3. Specify parameters (copy the actual parameters to the specified formal parameters)
4. Dynamic Parameters:
*args position parameters are all placed in tuples by default
**kwargs Default keyword parameters (dictionaries), all in the dictionary
5. Universal Parameters
1.1.2 Local Variables

1. Variables defined in the program become local variables.
2. A local variable scope is a subroutine that defines the variable.
3. When a global variable conflicts with a local variable, local variables work within the subroutine that defines the local variables, and the global variables function elsewhere.

#!/usr/bin/env python
# Author:xuliangwei
Name = "Xuliangwei"
def change_name (name):
Print ("Before change:", name)
Name = "I am a man with Tesla" #定义局部变量
Print ("After Chage:", name)
Change_name (name)
Print ("Look outside name changed?", name)
Execution Result:

Before Change:xuliangwei
After Chage: I'm a man with Tesla.
Did you see the name change outside? Xuliangwei
1.1.3 Global Variables

1. Variables defined at the beginning of a program are called global variables.

1. Global variables define variables and must all be uppercase (unspoken rules). For example: Name= "Xuliangwei"
2. The function first reads the current environment variable, and if it does not, it reads the global variable, and the global variable is readable at all scopes.
3. Modifying global variables requires the first global name, which means that name is a global variable (re-assigned value).
4. Special: list, dictionary, tuple nested list, can be modified, not re-assigned value.
1.1.4 built-in functions

# all #非0即真
# any #
# bool #0和, empty dictionary empty list is False
# callable #表示是否可执行, or whether you can call
# dir #快速查看对象提供了哪些功能
# Divmod #文章分页使用
# Isinstance #用于判断 Whether an object is an instance of a class
# Globals #列出全局变量
# Locals #列出所有局部变量
# hash #
#enumerate
#float
#format
#frozenset
# Max #最大
# min #最小
# sum #求和
# int #整数
# hex #十进制转换十六进制
# bin #十进制转二进制
# Oct #十进制转十进制
# filter #内部循环, parameter comparison
# map #将函数返回值添加到结果中
# compile #将字符串, compiled into Python code
# eval #执行表达式, and get results
# exec #执行Python代码, receive: Code or string
#id #查看内存地址
#input #等待用户输入
# isinstance #查看某个对象是不是某个类的实例
# issubclass #
# len #查看长度
# list #
# Memoryview #查看内存地址相关类
# next #
# iter #创建迭代器
# object #所有类的复类
# Open #
# ord #
# POW #
# Print #
# property #
# range #
# repr #
# Reversed #反转
# round #
# set #集合
# slice #
# sorted #
# Staticmethod #
# str #字符串
# Super #面向对象
# tuple #元祖
# type #类型
# VARs #当前模块有哪些变量
# Zip #压缩
# __import__ #导入模块
# delattr ()
# getattr ()
# setattr ()
1.1.5 function return value

To get the result of the function execution, you can return the result with a return statement.

1. The function will stop executing and return the result as soon as it encounters a return statement, or it can be understood that the return statement represents the result of the function.
2. If return is not specified in the function, the return value of this function is none.
1.1.6 recursive function

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

#!/usr/bin/env python
# Author:xuliangwei
Def calc (n):
Print (n)
if int (N/2) ==0:
return n
Return calc (int (N/2))
Calc (10)
Recursive features:
1. There must be a clear end condition.
2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion.
3. Recursive efficiency is not high, too many recursive hierarchy will lead to the benefit of the stack (in the computer, the function call is implemented through the data results stack (stack), whenever a function call, the stack will add a stack of frames, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, the number of recursive calls is too many and can lead to stack benefits. )

1.1.7 Anonymous functions

An anonymous function is a specified function that does not need to be displayed

#!/usr/bin/env python
# Author:xuliangwei
Def calc (n):
Return N**n
Print (Calc (10))
#换成匿名函数
Calc = Lambda n:n**n
Print (Calc (10))
#从上看来好像并无卵用, if that's the case, there is no improvement in hair, but the anonymous function is used in conjunction with other functions as follows:
res = map (lambda x:x**2,[1,5,7])
For I in Res:
Print (i)
#结果:
1
25
49
1.1.8 Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

#!/usr/bin/env python
# Author:xuliangwei
def add (x,y,f):
return f (x) + f (Y)
res = Add (3,-6,abs)
Print (RES)
1.1.9-Functional programming

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functional programming, although it can be attributed to process-oriented programming, but the idea is closer to the mathematical calculation.
We first have to understand the concepts of computer (computer) and computational (Compute).
At the level of the computer, the CPU executes the subtraction instruction code, as well as various conditional judgments and jump instructions, so, assembly language is the most close to the computer languages.
And the calculation of the exponential meaning, the more abstract calculation, the farther away from the computer hardware.

Functional programming is a very high degree of abstraction of the programming paradigm, the purely functional programming language functions are not variable, so any function, as long as the input is determined, the output is OK, this pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.
One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned!
Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

(1 + 2) * 3-4
#传统的过程式编程, it may be written like this:
var a = 1 + 2;
var B = A * 3;
var c = b-4;
#函数式编程要求使用函数, we can define the operation process as a different function, as follows:
var result = Subtract (multiply (add), 3), 4);
#这就是函数式编程 (that's how much)
1.2 Decorators

1. Automatically executes the XX function and passes the function name F1 below as a parameter
2. Re-assign the return value of the XX function
Definition: Essentially a function, (decorating other functions) is a function of adding attachments to other functions.

1. Cannot modify the source code of the decorated function
2. Cannot modify the calling mode of the decorated function
Implement the Adorner Knowledge Reserve:

1. function is "variable"
2. Higher-order functions
3. Nesting functions
Advanced functions + nested functions = = Adorner
No parameters and no nested function adorners
def foo (func):
Print
' Decorator Foo '
return func
@foo
def bar ():
Print
' Bar '
Bar ()
# There are no nested functions, adding the ability to print "decorator foo" without changing the way the function is called.
No parameter adorner (no parameters)
#!/usr/bin/env python
# Author:xuliangwei
Import time
def decorator (func):
def wrapper (*args, **kwargs):
Start = Time.time ()
Func (*args, **kwargs)
Stop = Time.time ()
Print (' Run time is%s '% (Stop-start))
Print ("timeout")
Return wrapper
@decorator # Decorators
def test (list_test):
For I in List_test:
Time.sleep (0.1)
Print ('-' *, i)
# Decorator (test) (range (10))
Test (range (10))
# you can see the adorner decorator with no parameters
Parametric adorner (no parameters)
Import time
def timer (timeout=0):
def decorator (func):
def wrapper (*args, **kwargs): # will pass parameters to the adorner because it is not possible to determine how many parameters the adorner has, so use this.
Start = Time.time ()
Func (*args, **kwargs)
Stop = Time.time ()
Print (' Run time is%s '% (Stop-start))
Print (timeout)
Return wrapper
return decorator
@timer (2) # Adorner parameter is 2
def test (list_test):
For I in List_test:
Time.sleep (0.1)
Print ('-' *, i)
# timer (timeout=10) (test) (range (10))
Test (range (10))
# Adorner timer has a parameter of 2, @timer (2) equivalent to Test=timer (2) (test)
1.3 iterators

We already know that there are several types of data that can be directly applied to a For loop:
A class is a collection of data types, such as list, tuple, dict, set, str, and so on;
A class is generator, including generators and generator function with yield.
These objects that can directly act on a for loop are called an iterative object: Iterable.
You can use Isinstance () to determine whether an object is a Iterable object:

xuliangwei:~ xuliangwei$ Python3
>>>
>>> from collections Import iterable
>>> isinstance ([], iterable)
True
>>> isinstance ({}, iterable)
True
>>> isinstance (' abc ', iterable)
True
>>> Isinstance ((x for X in range), iterable)
True
>>> isinstance (iterable)
False
The generator can not only be used for a for loop, but it can also be called by the next () function and return the next value until the last throw Stopiteration error indicates that the next value cannot be returned again.

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.
You can use Isinstance () to determine whether an object is a iterator object:

xuliangwei:~ xuliangwei$ Python3
>>>
>>> from collections Import Iterator
>>> Isinstance ((x for X in range), Iterator)
True
>>> isinstance ([], Iterator)
False
>>> isinstance ({}, Iterator)
False
>>> isinstance (' abc ', Iterator)
False
You might ask, why are data types such as list, dict, and str not iterator?

This is because the Python iterator object represents a data stream, and the iterator object can be called by the next () function and continuously return to the next data until the Stopiteration error is thrown when there is no data. This data stream can be viewed as an ordered sequence, but we cannot know the length of the sequence in advance, but we will only continue to calculate the next data on demand through the next () function, so the calculation of iterator is inert and is only calculated when the next data needs to be returned.

Iterator can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.

Summary
All objects that can be used for a for loop are iterable types;
All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;
Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.
Python's for loop is essentially implemented by constantly invoking the next () function, for example:
For x in [1, 2, 3, 4, 5]:
Pass
is actually exactly equivalent to:

# Get the Iterator object first:
it = iter ([1, 2, 3, 4, 5])
Cycle
While True:
Try
# Get the next value:
x = Next (IT)
Except stopiteration:
# exit the loop when you encounter stopiteration
Break
1.4 Generators

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

There are a number of ways to create a generator. The first method is simple, as long as a list-generated [] is changed to (), a generator is created:

L = [x * x for x in range (10)]
Print (L)
g = (x * x for x in range (10))
Print (g)
#执行结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator Object <genexpr> at 0x101380938>
1. The corresponding data is generated only at the time of the call.
Only the current location is recorded.
There is only one next () method. Next ()

Python section Fourth

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.