Abstraction
Laziness is a virtue.
Abstraction and Structure
Abstract can save a lot of work. In fact, it has a greater role. It is the key to making computer programs understandable.
Create a function
A function can be called (which may contain parameters, that is, values placed in parentheses). It performs a certain action and returns a value. In general, the built-in callable function can be used to determine whether the function is callable:
>>> Import math
>>> Y = 1
>>> X = math. sqrt
>>> Callable (x)
True
>>> Callable (y)
False
Creating a function is the key to organizing a program. So how to define a function?
Use the def (or "Function Definition") Statement:
>>> Def hello (name ):
Return 'hello, '+ name + '! '
Input different parameters to get different results:
>>> Print hello ('signature ')
Hello, signjing!
>>> Print hello ('jiao ')
Hello, jiao!
The method for obtaining the Fibonacci series (for example, the first 10 items) is:
>>> F = [0, 1]
>>> For I in range (8 ):
F. append (f [-1] + f [-2])
>>> Print f
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
If it is implemented using the function method, it is:
>>> Def fibs (num ):
Result = [0, 1]
For I in range (num-2 ):
Result. append (result [-2] + result [-1])
Return result
Execution result:
>>> Fiber (10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> Fiber (16)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144,233,377,610]
Return statements are used to return values from functions.
Record Function
If you want to write a document to the function to make it understandable to those who use the function later, you can add comments (starting ).
Another way is to write strings directly. Here, strings may be very useful elsewhere, for example, after the def Statement (and at the beginning of the module or class ). If you write a string at the beginning of a function, it will become a part of the function for storage, known as the document string.
>>> Def fibs (num ):
'Oss is a funtion :*************'
Result = [0, 1]
For I in range (num-2 ):
Result. append (result [-2] + result [-1])
Return result
>>> Fibs. _ doc __
'Oss is a funtion :*************'
Note: __doc _ is a function attribute.
The built-in help function is very useful. Use it in the interactive interpreter to obtain information about the function, including its document string.
>>> Help (fiber)
Help on function fibs in module _ main __:
Fibs (num)
Fibs is a funtion :*************
Functions that are not real functions
In a mathematical sense, a function always returns a vertex after calculating its parameters. Some functions in python do not return anything.
There is no return statement, or there is a return statement, but the return is not followed by a function with any value.
>>> Def test ():
Print "This is printed"
Return
Print 'this is not'
>>> X = test ()
This is printed
The return Statement in the above functions only serves to end the function.
>>> X
>>> Print x
None
Therefore, all functions indeed return something: when they are not required to return a value, they return None.
Where does the parameter magic value come from?
A variable after a number in a def statement is usually called a function form parameter, and the value provided when a function is called is an actual parameter or a parameter.
Can I change the parameters?
Assigning a new value to a parameter in a function does not change the value of any external variable.
>>> Def try_to_change (n ):
N = "Hello, signjing"
>>> Say = "Hello, jiao"
>>> Try_to_change (say)
>>> Say
'Hello, jiao'
Strings (numbers and metadata) cannot be modified. Therefore, they do not need to be described when making parameters. However, what happens when a variable data structure such as a list is used as a parameter:
>>> Def change (n ):
N [0] = 'signature'
>>> Names = ['Li lei', 'Han meimei']
>>> Change (names)
>>> Names
['Signature', 'Han meimei']
Do not call the function again below:
>>> Names = ['Li lei', 'Han meimei']
>>> N = names
>>> N [0] = 'signature'
>>> Names
['Signature', 'Han meimei']
This has also happened before: When two variables reference a list at the same time, they do reference a list at the same time. To avoid this situation, you can copy a copy of the list. When slice is made in the sequence, the returned slice is always a copy. Therefore, if you copy the slice of the entire list, you will get a copy:
>>> N = names [:]
>>> N
['Li lei', 'Han meimei']
>>> Names
['Li lei', 'Han meimei']
>>> N is names
False
>>> M = n
>>> M is n
True
In some languages (such as c ++ and Ada), it is common to rebind parameters and make these changes affect variables outside the function. But it is impossible in python. A function can only modify the parameter object itself. But what if the parameter is unchangeable, such as a number? The answer is no way. At this time, all required values should be returned from the function. If there is more than one value, it will be returned in the form of tuples.
For example, the function that increases the value of a variable by 1 can be written as follows:
>>> Def inc (x): return x + 1
>>> Foo = 10
>>> Foo = inc (foo)
>>> Foo
11
If you really want to change the parameter, you can use a little trick to place the value in the list:
>>> Def inc (x): x [0] = x [0] + 1
>>> Foo = [10]
>>> Inc (foo)
>>> Foo
[11]
In this way, only new values are returned.
Keyword parameters and default values
Currently, all the parameters we use are called location parameters because their location is very important-in fact, they are more important than their names.
>>> Def hello_1 (greeting, name ):
Print '% s, % s' % (greeting, name)
>>> Def hello_2 (name, greeting ):
Print '% s, % s' % (name, greeting)
>>> Hello_1 ('hello', 'boys ')
Hello, boy
>>> Hello_2 ('hello', 'girl ')
Hello, girl
Sometimes (especially when there are many parameters), the order of parameters is hard to remember. To make things easier, you can provide the parameter name:
>>> Hello_1 (greeting = 'hello', name = 'boys ')
Hello, boy
>>> Hello_1 (name = 'boys', greeting = 'hello ')
Hello, boy
However, the parameter names and values must correspond:
>>> Hello_2 (name = 'boys', greeting = 'hello ')
Boy, hello
>>> Hello_2 (greeting = 'hello', name = 'boys ')
Boy, hello
The parameters provided by these parameter names are called keyword parameters. The main role is to clarify the role of each parameter.
The most powerful keyword parameter is that the default value can be provided to the parameter in the function. When a parameter has a default value, you do not need to provide IT when calling it. You may not provide, provide, or provide all the parameters:
>>> Def hello_3 (greeting = 'hello', name = 'World '):
Print '% s, % s! '% (Greeting, name)
>>> Hello_3 ()
Hello, world!
>>> Hello_3 ('greeting ')
Greeting, world!
>>> Hello_3 ('greeting ', 'Universe ')
Greeting, universe!
>>> Hello_3 (name = 'Boys ')
Hello, boys!
Location and keyword parameters can be used together. Place the location parameter in the front.
Note: Unless you fully understand the functions and meanings of the program, you should avoid mixing location and keyword parameters.
Collection Parameters
Sometimes it is useful to provide users with any number of parameters. Try to define a function like the following:
>>> Def print_params (* params ):
Print params
>>> Print_params (1, 2)
(1, 2)
>>> Print_params (1, 2, 'AB ')
(1, 2, 'AB ')
The asterisks before the parameter place all values in the same tuples. It can be said that these values are collected and then used.
>>> Def print_params_2 (title, * params ):
Print title
Print params
>>> Print_params_2 ('params: ', 1, 2, 3)
Params:
(1, 2, 3)
If no elements are provided for collection, params is an empty tuples:
>>> Print_params_2 ('Nothing :')
Nothing:
()
>>> Print_params_2 ('hmm... ', something = 42)
Traceback (most recent call last ):
File" ", Line 1, in
Print_params_2 ('hmm... ', something = 42)
TypeError: print_params_2 () got an unexpected keyword argument 'something'
We need another "Collection" operation that can process keyword parameters.
>>> Def print_params_3 (** params ):
Print params
>>> Print_params_3 (x = 1, y = 2, z = 3)
{'Y': 2, 'x': 1, 'z': 3}
Reversal Process
>>> Def add (x, y ):
Return x + y
>>> Params = (1, 2)
>>> Add (* params)
3
Used in a call, not in a definition.
The parameter list works normally, as long as it is extended to the latest part. You can use the same technology to process the dictionary-using the Double Star operator.
>>> Def hello_3 (greeting = 'hello', name = 'World '):
Print '% s, % s! '% (Greeting, name)
>>> Params = {'name': 'Sir Robin ', 'greeting': 'Well met '}
>>> Hello_3 (* params)
Name, greeting!
>>> Hello_3 (** params)
Well met, Sir Robin!
Asterisks are only useful when defining functions (parameters with an indefinite number are allowed) or calling ("split" dictionary or sequence.
Scope
The variable and the corresponding value use an "invisible" dictionary. In fact, this is very close to the real situation. The built-in vars function returns this dictionary:
>>> X = 1
>>> Scope = vars ()
>>> Scope ['X']
1
>>> Scope ['X'] + = 1
>>> X
2
These "invisible dictionaries" are called namespaces or scopes. How many namespaces are there? In addition to the global scope, each function call creates a new scope;
The working principle of a parameter is similar to that of a local variable. Therefore, it is no problem to use the name of a global variable as the parameter name.
What should I do if I need to access global variables inside the function? In addition, you only want to read the value of the variable (that is, you do not want to re-bind the variable). Generally, there is no problem:
>>> Def combine (parameter ):
Print parameter + external
>>> External = 'berry'
>>> Combine ('shrub ')
Shrubberry
Reading global variables is generally not a problem, but there is still a problem. If the names of local variables or parameters are the same as those of the global variables you want to access, you cannot directly access them. Global variables are blocked by local variables.
If necessary, you can use the globals function to obtain the global variable value. This function is close to vars and can return the global variable Dictionary (locals returns the local variable dictionary ).
Rebind a global variable (so that the variable references other new values): If a value is assigned to a variable within the function, it automatically becomes a local variable unless python is notified to declare it as a global variable.
>>> X = 1
>>> Def change_global ():
Global x
X = x + 1
>>> Change_global ()
>>> X
2
Recursion
I think of a joke:
To understand recursion, you must first understand recursion.
Okay, it's a bit cool. Continue to the hot topic ....
Recursive definitions (including recursive function definitions) include references to their own definitions.
You need to find the meaning of recursion. The result shows that recursion is infinite. A similar function is defined as follows:
>>> Def recursion ():
Return recursion ()
Obviously, it cannot do anything. Theoretically, it should always run.
Since each function call will use a little memory, after enough function calls occur, the space is insufficient. The program ends with an error message "beyond the maximum recursion depth:
Traceback (most recent call last ):
File" ", Line 1, in
Recursion ()
File" ", Line 2, in recursion
Return recursion ()
......
File" ", Line 2, in recursion
Return recursion ()
RuntimeError: maximum recursion depth exceeded
This type of recursion is called infinite recursion. It is similar to an infinite loop starting with while True. There is no break or return statement in the middle.
Useful recursive functions include the following:
When the function returns a value directly, there is a basic instance (minimum possibility problem );
Recursive instances, including recursive calls of the smallest part of one or more problems;
Two classics: factorial and power
>>> Def factorial (n ):
Result = n
For I in range (1, n ):
Result * = I
Return result
>>> Factorial (5)
120
Recursive Implementation:
>>> Def factorial (n ):
If n = 1:
Return 1
Else:
Return n * factorial (n-1)
>>> Factorial (4)
24
>>> Def power (x, n ):
Result = 1
For I in range (n ):
Result * = x
Return result
>>> Power (5, 3)
125
Recursive Implementation:
>>> Def power (x, n ):
If n = 0:
Return 1
Else:
Return x * power (x, n-1)
>>> Power (4, 4)
256
Another classic: Binary Search
Omitted here;
Object magic
Creating your own objects (especially types or objects called classes) is the core concept of python-very core.
The term objects in Object-Oriented Programming can basically be seen as a collection of data (features) and a series of methods that can access and operate the data.
Objects have the following advantages:
Polymorphism: the same operation can be performed on objects of different classes;
Encapsulation: hiding the details of objects in the external world;
Inheritance: a special class object is created based on a common class;
What are classes and types?
Class is an object. All objects belong to a class and become instances of the class.
When an object belongs to a class that belongs to another object, the former is called the Child class of the latter. On the contrary, the latter is called the superclass (base class) of the former ).
In object-oriented programming, the relationship between subclasses is implicit, because the definition of a class depends on the methods it supports. Defining a subclass is only a process of defining more (or possibly an existing overload) methods.
Create your own class
>>> _ Metaclass _ = type
>>> Class Person:
Def setName (self, name ):
Self. name = name
Def getName (self ):
Return self. name
Def greet (self ):
Print "Hello, world! I'm % s. "% self. name
>>> Foo = Person ()
>>> Bar = Person ()
>>> Foo. setName ('abc ')
>>> Foo. getName ()
'Abc'
>>> Foo. greet ()
Hello, world! I'm abc.
Self is a reference to the object itself. Without it, the member method will not be able to access the object they want to operate on its features.
Special effects, functions, and methods
By default, a program can access the features of an object from outside.
To change a method or feature to private (inaccessible from external sources), simply add a Double underline before its name:
>>> Class Secretive:
Def _ inaccessible (self ):
Print "Bet you can't see me ..."
Def accessible (self ):
Print "The secret message is :"
Self. _ inaccessible ()
>>> S. _ inaccessible ()
Traceback (most recent call last ):
File" ", Line 1, in
S. _ inaccessible ()
AttributeError: 'secret' object has no attribute' _ inaccessible'
>>> S. accessible ()
The secret message is:
Bet you can't see me...
In the internal definition of a class, all names starting with double underscores are "translated" into the form of a single underline and a class name added before:
>>> Secretive. _ Secretive _ inaccessible
In short, it is impossible to ensure that others do not access the methods and features of objects, but such "name change techniques" mean that they should not access these functions or features as powerful signals.
Class namespace
Class definition is actually the Execution code block, which is very useful.
Specify the superclass
To write other class names in parentheses after the class statement, you can specify the superclass:
>>> Class Filter:
Def init (self ):
Self. blocked = []
Def filter (self, sequence ):
Return [x for x in sequence if x not in self. blocked]
>>> Class SPAMFilter (Filter ):
Def init (self ):
Self. blocked = ['spam']
Filter is a general class used to Filter sequences. In fact, it cannot Filter anything:
>>> F = Filter ()
>>> F. init ()
>>> F. filter ([1, 3, 4])
[1, 3, 4]
The Filter class can be used as the base class (superclass) of other classes. It can Filter out the "SPAM" in the sequence.
>>> S = SPAMFilter ()
>>> S. init ()
>>> S. filter (['abc', 'spam', "SPAM", 'spam', 'signjing '])
['Abc', 'signature']
Investigation inheritance
To check whether a class is another subclass, you can use the built-in issubclass function:
>>> Issubclass (SPAMFilter, Filter)
True
>>> Issubclass (Filter, SPAMFilter)
False
If you want to know the base classes of known classes, you can directly use its special features _ bases __:
>>> SPAMFilter. _ bases __
( ,)
>>> Filter. _ bases __
( ,)
You can also use the isinstance method to check whether an object is an instance of a class:
>>> Isinstance (s, SPAMFilter)
True
>>> Isinstance (s, Filter)
True
>>> Isinstance (s, str)
False
S is a (direct) Member of the SPAMFilter class, but is also an indirect Member of the Filter class, because SPAMFilter is a subclass of the Filter.
If you want to know which class an object belongs to, you can use the _ class _ feature:
>>> S. _ class __
Multiple superclasses
>>> Class Calculator:
Def calculate (self, expression ):
Self. value = eval (expression)
>>> Class Talker:
Def talk (self ):
Print 'Hi, my value is ', self. value
>>> Class TalkingCalculator (Calculator, Talker ):
Pass
There can be multiple superclasses.
Here, the subclass does not do anything and inherits all the actions from its own superclass.
This behavior becomes a multi-inheritance and is a very useful tool.
Note the following when using multi-inheritance. If a method inherits from multiple superclasses, you must note the superclasses order:
The methods in the inherited class will be overwritten and then the methods in the inherited class.