Python learning notes for beginners

Source: Internet
Author: User
Tags abs bind function definition generator inheritance iterable stdin in python

Python basics

A string is any text enclosed by single quotation marks or double quotation marks, such as 'ABC' and "xyz.

If 'is also a character, it can be enclosed by "". For example, "I'm OK" contains the characters I,', m, space, O, k, Six Characters

What if the string contains both 'and? It can be identified by escape characters \, for example:

1
'I \'m \ "OK \"! '
The string content is:

1
I'm "OK "!
A null value is a special value in Python, expressed as None. None cannot be understood as 0, because 0 is meaningful, and None is a special null value.

List and tuple

List is an ordered set. You can add or delete elements at any time, such as classmates = ['Michael ', 'Bob', 'Tracy'].
Tuple and list are very similar, but once the tuple is initialized, it cannot be modified, indicating that such as classmates = ('Michael ', 'Bob', 'Tracy ')
What is the significance of an immutable tuple? Because tuple is immutable, the code is safer. If possible, use tuple instead of list.

A comma must be added when only one tuple element is defined. Otherwise, tuple is not defined, but the element itself.
Notes for Python functions

Required parameter before, default parameter after, otherwise the Python interpreter will report an error

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple when the function is called in the form of * args

Keyword parameters allow you to input 0 or any parameter with the parameter name. These keyword parameters are automatically assembled into a dict in the function in the ** kw mode.

When using the named keyword parameter, note that if there is no variable parameter, you must add a * as a special separator. If * is missing, the Python interpreter cannot identify location parameters and naming keyword parameters.

The order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, name keyword parameter, and keyword parameter

Any function can be called in a way similar to func (* args, ** kw), regardless of how its parameters are defined.

Advanced features

Generator

Generator: one-side cyclic computing mechanism

Create a generator

Change [] of a list generator ()

>>> L = [x * x for x in range (10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> G = (x * x for x in range (10 ))
>>> G
<Generator object <genexpr> at 0x1022ef630>
If a function definition contains the yield keyword, this function is no longer a common function, but a generator.

The execution process of generator and function is different. The function is executed sequentially. If a return statement or the last row of the function statement is returned. The generator function is executed every time next () is called. When the yield statement is returned, the yield statement returned last time is executed again.


Def odd ():
Print ('step 1 ')
Yield 1
Print ('step 2 ')
Yield (3)
Print ('Step 3 ')
Yield (5)
When calling this generator, you must first generate a generator object, and then use the next () function to continuously obtain the next return value:


>>> O = odd ()
>>> Next (o)
Step 1
1
>>> Next (o)
Step 2
3
>>> Next (o)
Step 3
5
>>> Next (o)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
StopIteration
Iterator

All objects that can act on the for loop are of the Iterable type;
All objects that can act on the next () function are of the Iterator type. They represent a sequence of inert computing;
Set data types such as list, dict, and str are Iterable but not Iterator. However, you can use the iter () function to obtain an Iterator object.
High-order functions

Pass functions as parameters. Such functions are called high-order functions. Functional programming refers to this highly abstract programming paradigm.


Def add (x, y, f ):
Return f (x) + f (y)

>>> Add (-5, 6, abs)
11
Map/reduce

The map () function receives two parameters. One is a function and the other is Iterable. The map function sequentially applies the input function to each element of the sequence and returns the result as a new Iterator.

Convert all the numbers in the list into strings:

1
2
>>> List (map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Reduce acts a function on a sequence [x1, x2, x3,...] this function must receive two parameters. reduce calculates the result continuation and the next element of the sequence. The effect is:

Reduce (f, [x1, x2, x3, x4]) = f (x1, x2), x3), x4)

For example, convert str to int:


>>> From functools import reduce
>>> Def fn (x, y ):
... Return x * 10 + y
...
>>> Def char2num (s ):
... Return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} [s]
...
>>> Reduce (fn, map (char2num, '20140901 '))
13579
Filter


'Filter () 'applies the input function to each element in sequence, and determines whether to retain or discard the element based on whether the returned value is 'true' or 'false'.


For example, to delete an even number in a list, only the odd number is retained. You can write this statement:

Def is_odd (n ):
Return n % 2 = 1
List (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# Result: [1, 5, 9, 15]
Note that the filter () function returns an Iterator, that is, an inert sequence. To force the filter () to complete the calculation result, you must use the list () function to obtain all the results and return the list.

Sorted


Sort by absolute value:

>>> Sorted ([36, 5,-12, 9,-21], key = abs)
[5, 9,-12,-21, 36]
Return function

A function can return a calculation result or a function.

When returning a function, remember that the function is not executed. Do not reference any variable that may change in the returned function.

Closure:

Def foo ():
M = 3
N = 5
Def bar ():
A = 4
Return m + n +
Return bar
>>> Bar = foo ()
>>> Bar ()
12

Bar is defined in the code block of the foo function. Bar is the internal function of foo.

In the local scope of bar, you can directly access the m and n variables defined in the foo local scope.
Simply put, this internal function can use the behavior of external function variables, called closures.

Partial function


When the number of parameters of a function is too large and needs to be simplified, use 'functiontools. partial 'can create a new function, which can fix some parameters of the original function, making it easier to call.

>>> Import functools
>>> Int2 = functools. partial (int, base = 2)
>>> Int2 ('20140901 ')
64
>>> Int2 ('20140901 ')
85
Module

In Python, A. py file is called a Module)

There will be a _ init _. py file under each package directory, __init _. py itself is a module, and the module name is the package name

Functions or variables such as _ xxx and _ xxx are non-public (private) and should not be directly referenced, such as _ abc ,__ abc.

The reason we say that private functions and variables should not be directly referenced, rather than being directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, however, in programming habits, private functions or variables should not be referenced.

Object-oriented

In Python, if the instance variable name starts with _, it becomes a private variable, which can only be accessed internally and cannot be accessed externally.

Restrict instance attributes: defines a special _ slots _ variable to limit the attributes that can be added to this class instance.

Class Student (object ):
_ Slots _ = ('name', 'age') # use tuple to define the names of attributes that can be bound

Then, let's try:

>>> S = Student () # Create a new instance
>>> S. name = 'Michael '# bind the property 'name'
>>> S. age = 25 # bind the property 'age'
>>> S. score = 99 # bind the attribute 'score'
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'Student 'object has no attribute 'score'
Convert a getter method to an attribute. You can add @ property to add @ score. setter to the attribute assignment of a setter method.

For example:

Class Student (object ):
@ Property
Def score (self ):
Return self. _ score
@ Score. setter
Def score (self, value ):
If not isinstance (value, int ):
Raise ValueError ('score must be an integer! ')
If value <0 or value> 100:
Raise ValueError ('score must between 0 ~ 100! ')
Self. _ score = value

External call


>>> S = Student ()
>>> S. score = 60 # OK, which is actually converted to s. set_score (60)
>>> S. score # OK, which is actually converted to s. get_score ()

Python allows multiple inheritance. This design is usually called MixIn.

Dynamically create class type ()


>>> Def fn (self, name = 'world'): # define the function first.
... Print ('Hello, % s. '% name)
...
>>> Hello = type ('hello', (object,), dict (Hello = fn) # Create a hello class
>>> H = Hello ()
>>> H. hello ()
Hello, world.
>>> Print (type (Hello ))
<Class 'type'>
>>> Print (type (h ))
<Class '_ main _. Hello'>

To create a class object, the type () function will input three parameters in sequence:

Class name;
A set of inherited parent classes. Note that Python supports multiple inheritance. If there is only one parent class, do not forget the single-element syntax of tuple;
The class method name is bound to the function. Here we bind the function fn to the method name hello.
IO programming

File read/write

In Python, file reading and writing is completed by opening file objects through the open () function. In Python, such objects are collectively referred to as file-like objects. In addition to file, it can also be a memory byte stream, network stream, custom stream, and so on.

It is a good habit to use the with statement to operate on file IO. It automatically calls the close () method, for example:


With open ('/path/to/file', 'r') as f:
Print (f. read ())

Multi-process

The Unix/Linux operating system provides a fork () system call, which is very special. A common function is called once and returns once, but fork () is called once and returns twice because the operating system automatically calls the current process (called the parent process) copy a copy (called a child process), and then return the results in the parent process and child process respectively.

The child process always returns 0, and the parent process returns the child process ID. The reason for doing so is that a parent process can fork many sub-processes, so the parent process needs to write down the ID of each sub-process, and the sub-process only needs to call getppid () you can get the ID of the parent process.

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.