preface
Part 1 Basic Python syntax
1. Know the Python
1.1 introduction of Python
Python’s design goal: a language that is simple and intuitive and as powerful as its main competitors and open source so that anyone can contribute to it code that is as easy to understand as plain English for the day-to-day tasks of short-term development
Python’s design philosophy: elegant, unambiguous, simple
The Philosophy of Python developers is: one way, preferably only one way, to do one thing
Extensibility: If you need a key piece of code to run faster or you want to keep some algorithms private, you can write it in C or C++ and use it in A Python program.
1.2. First Python program
ASCII characters contain only 256 characters and do not support Chinese characters
-
The interpreter name for Python 2.x is Python
-
The interpreter name for Python 3.x is python3
Note: If you cannot use Python 3.0 immediately (there are few third-party libraries that do not support the 3.0 syntax), you are advised to use Python 3.0 first and then use Python 2.6, Python 2.7, and do some compatibility processing
-
Graphical user interface
-
Code editor (code completion/auto indent support)
-
Compiler/interpreter
-
Debugger (breakpoint/step)
-
…
1.3. PyCharm setting
1.3.1 Restoring PyCharm initial Settings
-
Close PyCharm that is running
-
On the terminal, run the following terminal command to delete the PyCharm configuration directory:
$rm – r ~ /. PyCharm2016.3
-
Restart PyCharm
1.3.2 PyCharm Installation and Startup Procedure
-
Run the following command to decompress the downloaded installation package
$tar – ZXVF pycharm – professional – 2017.1.3. Tar. Gz
-
Move the decompressed directory to the /opt directory to facilitate other users
/opt directory The user stores additional software for the host
$sudo mv pycharm-2017.1.3/ /opt/Copy the code
-
Switching working Directory
$CD/opt/pycharm – 2017.1.3 / bin
-
Start the PyCharm
$ ./pycharm.sh
1.3.3 Setting the startup icon
-
In the Professional edition, select the menu Tools/Create Desktop Entry… You can set the taskbar startup icon
-
Note: Settings icon, need to check the Create the entry for all the users shortcut file/usr/share/applications/jetbrains – pycharm. The desktop
In Ubuntu, shortcuts to application startup are usually saved in the /usr/share/applications directory
Uninstall PyCharm from previous versions
-
Delete the decompressed directory
$sudo rm -r /opt/pycharm-2016.3.1/
-
Delete the hidden directory under the home directory that is used to save configuration information
$rm – r ~ /. PyCharm2016.3 /
Jetbrains – PyCharm. Desktop in /usr/share/applications/ should also be deleted if PyCharm is no longer used
1.4. Drill multi-file projects
-
A development project is to develop software that specifically solves a complex business function
-
Typically, each project has a separate directory for all project-related files
-
To make a Python program work in PyCharm, you must first right mouse click it
-
For beginners, in a project to set up more than one program can be executed, is very convenient, can facilitate the practice and test of different knowledge points
-
For commercial projects, there is usually only one Python source that can be executed directly within a project
2. Comment
-
The function of annotations is to use their familiar language to annotate some code in the program and enhance the readability of the program
2.1 Single Line Comment (Line comment)
-
Everything to the right of the # is treated as a caption, not as an actual program to be executed, but as an auxiliary illustration
Print (” Hello python”) # print hello Python
To ensure readability of the code, it is recommended to add a space after the # before writing the corresponding caption; To ensure readability, there should be at least two Spaces between comments and code.
2.2 Multi-line comments (block comments)
-
To use multi-line comments in Python programs, use a pair of three consecutive quotation marks (single and double quotation marks work)
“”” This is a multi-line comment and in between multi-line comments you can write a lot of things… “”” print(“hello python”)
-
More comments are not always better, and you don’t need to add comments for self-explanatory code
-
For complex operations, several lines of comment should be written before the operation begins
-
For code that is not self-explanatory, add a comment at the end of the line (comments should be at least 2 Spaces away from the code for readability)
-
Never describe the code. Assume the person reading the code knows Python better than you do. They just don’t know what your code does
2.3 Code Specification:
-
Python provides a series of Python Enhancement Proposals (PEP). The eighth part of the document provides suggestions for Python code formats. https://www.python.org/dev/peps/pep-0008/, Google has a corresponding Chinese documents: http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
3. The operator
3.1 Arithmetic operators
3.2 Comparison (relation) operators
In Python 2.x, the <> operator can also be used to determine if it is not equal to! = is also used in Python 2.x to determine not equal
3.3 Assignment operators
-
In Python, you can assign a value to a variable using =. In order to simplify code, Python also provides a set of assignment operators that correspond to arithmetic operators. Note that assignment operators cannot be separated by Spaces.
3.4 Identity operators
-
Is is used to determine whether the object referenced by two variables is the same
-
== Is used to determine whether the values of the referenced variables are equal
3.5 Member operators
3.6 Logical operators
Otherwise, it returns False or x or y as long as one of x or y is True
False is returned only if x and y are both False not not x If x is True, False is returned
If x is False, return True
3.7 Operator priority
-
The following table is ranked from highest to lowest arithmetical priority:
< complement > program execution principle
-
The operating system first asks the CPU to copy the Python interpreter’s programs into memory
-
The Python interpreter tells the CPU to translate the code in a Python program from the top down, based on syntax rules
-
The CPU is responsible for executing the translated code
How big is the Python interpreter?
-
To view the size of the Python interpreter, run the following terminal command
1. Locate the interpreter
$ which python
2. View the Python file size (just a soft link)
$ ls -lh /usr/bin/python
3. Check the file size
$ls – lh/usr/bin/python2.7
4. The variable
4.1 Definition of Variables
-
In Python, each variable must be assigned a value before it can be used, and then the variable can be created
-
Variables can be defined using the results of other variables
-
A variable name defines a variable only when it first appears
Variable name = value
In the interactive way, if you want to view the contents of a variable, you can directly enter the name of the variable. You do not need to use print function to run the interpreter. If you want to output the contents of the variable, you must use print function
4.2 Variable types
-
There is no need to specify a type to define a variable in Python (as is required in many other high-level languages). Python can automatically deduce the type of data stored in the variable from the value to the right of the = = sign
-
Data types can be numeric and non-numeric numeric integers (int) : All integers in Python3 are represented as long integers. Therefore, long integers have no separate numeric type. Bool: True a non-zero number is True, False False 0. Complex: A complex number is a real floating-point number represented by an ordered pair of x + yj, where x and y are real numbers and j is an imaginary unit. Non-numeric: Some operators also support these data types. See 4.4.5.3 Operators. String (STR) : The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repeat operator. List tuple dict
Note: In Python 2.x, integers are also divided into: int (integer) long (long), depending on the length of the stored value.
-
Use the type function to view the type of a variable
In [1]: type(name)
< complement > Calculation between different types of variables
-
Numerical variables can be computed directly between them
-
In Python, two numeric variables are directly arithmetical
-
If the variable is a bool, the number True corresponds to is 1 and the number False corresponds to is 0
-
Use + concatenation strings between string variables
-
String variables can repeatedly concatenate the same string with an integer using *
-
No other calculations can be made between numeric variables and strings
< complement > Gets input from the keyboard: input
-
In Python, you can use the input function to wait for input from the user from the keyboard
-
Anything the user enters is considered a string by Python
String variable = input(” prompt: “)
< complement > type conversion function
Price = float(input(" please input price :"))Copy the code
< complement > format output: print
-
If you want to output both text information and data, you need to use formatting operators
-
% is known as the formatting operator, which is used to process the string whose format contains %. It is called the formatting string % and is used with different characters. Different types of data require different formatting characters
-
The syntax is as follows:
Print (” format string “% variable 1) print(” format string” % variable 1… )
4.4.5 Advanced application of common methods and variables
4.4.5.1 Built-in functions
4.4.5.2 slice
-
Slicing uses index values to limit the range, cutting out small strings from a large string
-
Lists and tuples are ordered collections that can be retrieved by index values
-
A dictionary is an unordered collection that uses key-value pairs to hold data
-
Process oriented – How? According to the development requirements, some functionally independent code is packaged into one function after another. Finally completed code is to call different function features sequentially: If the requirements are complex, the code will become very complex. If there is no set formula, it will be very difficult to develop a complex project!
-
Object oriented – Who will do it? Compared to functions, object orientation is a larger encapsulation, encapsulating multiple methods in an object according to their responsibilities. Before completing a requirement, define responsibilities — things to do (methods) Determine different objects according to their responsibilities, encapsulate different methods (multiple) within the object and finally complete the code. It is to make different objects call different methods in sequence. It pays attention to objects and responsibilities, and different objects assume different responsibilities, which is more suitable for dealing with complex demand changes. It is specialized in dealing with complex project development
-
Class and Object A class is an abstract general term for a group of things that have the same characteristics or behavior. The characteristics are called properties and the behavior is called methods. An object is a concrete being created by a class. It is an instantiation of the class. In program development, to design a class, you usually need to satisfy the following three elements: the name of something like the class name, the name of something that satisfies the big hump nomenclature property, what kind of characteristics does something like that have, what kind of behavior does a method have
2. Object-oriented basic syntax
2.1 DIR Built-in functions and methods
-
Enter a dot. After the identifier/data and press the TAB key, and iPython prompts you for a list of methods that the object can call.
-
You can view all properties and methods within an object by passing in an identifier/data using the built-in function dir. Methods that hint at __ method names in __ form are built-in methods/properties provided by Python.
2.2 Defining a simple class (containing only methods)
Object orientation is more encapsulation, encapsulating multiple methods in a class so that objects created from that class can call those methods directly!
Def method 1(self, argument list): pass def method 2(self, argument list): passCopy the code
Object variable = class name ()Copy the code
In object-oriented development, the concept of references is equally applicable!
Tip: In computers, memory addresses are usually represented in hexadecimal notation.
Class Cat: def __init__(self, new_name): self.name = new_name print("%s "% self.name) def __del__(self): Print ("%s "% self.name) def __str__(self): return "%s "% self.name = Cat("Tom")Copy the code
Note: the __str__ method must return a string.
2.3 The self argument in the method
Def eat(self): print(self) def drink(self): Name = "Tom" print(" Tom") Tom = Cat()#Copy the code
The self inside the method is a reference to which object calls the method
-
Inside the method encapsulated by the class, self represents the object that is currently calling the method itself, and inside the method: through self. Access properties of an object, or call other methods of the object through self.
-
When calling a method, the programmer does not need to pass the self argument.
-
Outside the class, through the variable name. Access the properties and methods of an object in a class-wrapped method, via self. Access the properties and methods of an object
2.4 Initialization Method:init
-
When an object is created using the class name (), the following operations are automatically performed: Allocating space in memory for the object — creating the object sets initial values for the object’s properties — initializing methods (__init__)
The __init__ method is specifically used to define which properties a class has!
-
A property is defined by using self. property name = the initial value of the property inside the __init__ method. After the property is defined, objects created using the class will have the property.
-
In development, if you want to set the properties of an object at the same time as the object is created, you can modify the __init__ method by defining the property values you want to set as arguments to the __init__ method and using self inside the method. Attribute = parameter Receives externally passed arguments using the class name when creating an object (attribute 1, attribute 2…) call
Class Cat: def init(self, name): print(” %s” % name) self.name = name… tom = Cat(“Tom”) … Lazy_cat = Cat(” lazy Cat “)…
2.5 Private Properties and private methods
-
In real development, some properties or methods of an object may be intended to be used only inside the object, but not accessed externally
-
A private property is a property that an object does not want to make public
-
Private methods are methods that an object does not want to be exposed
-
When defining a property or method, add two underscores to the property or method name to define a private property or method:
Print (xiaofang._women__age) print(xiaofang._women__age)Copy the code
Tip: In everyday development, do not use this method to access private properties or methods of objects.
3. Encapsulation, inheritance and polymorphism
-
Encapsulate properties and methods into an abstract class based on responsibilities
-
Inheritance enables the reuse of code. The same code does not need to be written repeatedly
-
Polymorphic objects call the same method, resulting in different execution results, increasing the flexibility of the code
3.1 inheritance
3.1.1 single inheritance
Class Class name (parent class name): passCopy the code
-
Overriding methods of the parent class: the method implementation of the parent class is completely different from the method implementation of the child class. It is equivalent to defining a method with the same name as the parent class and implementing it.
-
Extending a parent class method: the method implementation of a subclass that contains the parent class overrides the parent class method in the subclass; Use the super(). Superclass method where needed to call the superclass method’s execution code; Other places write subclass-specific code implementations for the needs of subclasses.
About super
-
Super is a special class in Python
-
Super () is an object created using the super class
-
The most commonly used scenario is to call the method implementation encapsulated in the parent class when overriding a parent class method
Another way to call a superclass method: In Python 2.x, if you need to call a superclass method, you can also use the following method: superclass name. Method (self). This is currently supported in Python 3.x, but is not recommended because the name of the class where the method is called also needs to be changed if the parent class changes.
Private attributes and private methods of the parent class
Private properties and methods are private to the object and are not public to the outside world or subclasses. Methods are usually used to do internal things
3.1.2 multiple inheritance
Class Subclass name (parent 1, parent 2...) : passCopy the code
MRO in Python (Method Resolution Order)
-
If a method of the same name exists in a different parent class, which parent class does the subclass object call when it calls a method? Tip: Try to avoid this confusion when developing! Avoid multiple inheritance if there are attributes or methods with the same name between parent classes.
-
Python provides a built-in __mro__ attribute for classes that allows you to see the order in which methods are searched. When searching for methods, the mrO output is executed from left to right. If it finds a method in the current class, it executes the search, and if it doesn’t find one, If the last class is found and no method is found, the program reports an error
MRO is method Resolution Order (MRO). MRO is a method resolution order (MRO). MRO is a method resolution order (MRO)
New and old (classic) classes
-
New class: Classes based on Object, recommended
-
Classic class: Classes that do not have object as their base class. This class is not recommended
When you define a class in Python 3.x, if you do not specify a parent class, object is used as the base class by default. Object is not used as the base class.
-
To make sure you write code that runs in Both Python 2.x and Python 3.x! When defining a class in the future, if there is no parent class, it is recommended to inherit from object:
Class Class name (object): pass
Object is Python’s base class for all objects, with built-in properties and methods that can be viewed using the dir(object) function.
3.2 polymorphic
-
Encapsulation Criteria that define a class by encapsulating properties and methods into an abstract class based on responsibilities
-
Inheritance enables the reuse of code, the same code does not need to be repeatedly written design class skills subclass for their own unique needs, write specific code
-
Polymorphic subclass objects call the same superclass method, resulting in different execution results increase code flexibility the trick of calling a method on the premise of inheriting and overwriting the superclass method does not affect the internal design of the class
Polymorphism makes it easier to write common code and make common programming to adapt to changing requirements!
Class attributes and class methods
4.1 Class structure
In Python everything is an object: class AAA: The defined class belongs to the class object obj1 = AAA() belongs to the instance object
4.2 Class attributes and instance Attributes
Property acquisition mechanism
-
Class name. Class attribute
-
Object. Class attributes (not recommended if you use objects. Class attribute = value assignment statement, which adds only one attribute to the object and does not affect the value of the class attribute.
4.3 Class methods and static methods
This kind of method
-
A class property is a property defined for a class object. Using an assignment statement under the class keyword, you can define a class property to record the characteristics associated with that class
-
A class method is a method defined on a class object that can access class properties or call other class methods directly from within the class method
@classmethod def CLS: passCopy the code
-
A classmethod needs to be identified with the @classmethod decorator to tell the interpreter that it is a classmethod
-
The first argument to a class method should be the method that the CLS is called by, and the CLS inside the method is the reference to that class and the first argument to the instance method is self and you can use any other name like hint, but CLS is more common
-
Call the class method by the class name. When calling the method, you do not need to pass the CLS parameter
-
Class attributes can be accessed inside a method through CLS. Call other class methods
-
Define a tool class, and each tool has its own name
-
Requirement – Encapsulates a show_tool_count class method in a class that prints the number of objects created using the current class
@classmethod def show_tool_count(CLS): “”” print(” %d” % cls.count)
4.3.2 Static method
-
At development time, if you need to encapsulate a method in a class, the method does not need to access the instance properties or call the instance methods or the class properties or call the class methods
-
At this point, you can wrap the method as a static method
@staticmethod def staticmethod name: passCopy the code
-
A staticmethod needs to be identified with the @staticmethod decorator to tell the interpreter that it is static
-
Call a static method by class name
-
Static method show_help displays game help information
-
The class method show_top_score shows the highest score in history
-
Instance method start_game starts the game for the current player
-
Instance methods — Methods need access to instance properties internally. Instance methods can use class names internally. Accessing class attributes
-
Class methods – Only class attributes need to be accessed inside the method
-
Static methods – Inside methods, there is no need to access instance and class properties
5. The singleton
5.1 Singleton design Pattern
-
Design patterns Design patterns are the summary and extraction of previous work. Generally, the design patterns widely circulated by people are mature solutions to a specific problem. Design patterns are used in order to reuse code, make it easier for others to understand, and ensure the reliability of the code
-
The purpose of the singleton design pattern is to have the class create objects that are returned by a unique instance in the system each time the class name () is executed with the same memory address
-
Application scenario of singleton design mode Music player object Recycle bin object printer object……
5.2 Static Method:new
-
When an object is created using the class name (), the Python interpreter first calls the __new__ method to allocate space for the object
-
__new__ is a built-in static method provided by the object base class. It does two things: allocates space in memory for an object and returns a reference to the object
-
When the Python interpreter gets a reference to an object, it passes the reference as the first argument to the __init__ method
The code for overriding the __new__ method is very fixed!
-
Overriding the __new__ method must return super().__new__(CLS), otherwise the Python interpreter will not call the object’s initialization method without a reference to the allocated object
-
Note: __new__ is a static method that needs to actively pass the CLS arguments when called
5.3 Singleton in Python
-
Singletons — Let a class create an object that has a unique instance in the system that defines a class property. The initial value is None, which is used to record the reference to the singletons. Override the __new__ method. Recording the result in the class property returns a reference to the object recorded in the class property
Only one initialization is performed
-
Each time an object is created using the class name (), the Python interpreter automatically calls two methods: __new__ space allocation __init__ object initialization
-
After modifying the __new__ method, you get a reference to the object that was first created each time
-
But: the initialization method is called again
-
Let the initialization action be performed only once
-
Defines a class attribute, init_flag, to indicate whether an initialization action has been performed, with an initial value of False
-
In the __init__ method, determine init_flag and initialize if False
-
Then set init_flag to True
-
This way, when the __init__ method is called automatically again, the initialization action will not be performed again
Tips
Def input_password(): # 1\. Def input_password(): Prompt user for password PWD = input(" Please enter password: ") # 2\. If len(PWD) >= 8: return PWD # 3\. Ex = Exception(" Password length is not enough ") # 2> Raise an Exception object raise ex try: User_pwd = input_password() print(user_pwd) except Exception as result: print(" error: %s" % result)Copy the code
When comparing None in Python, it is recommended to use the IS judgment
Never use eval to convert input results directly. For example:
__import__ (' OS). The system (the 'ls') # import OS OS. The equivalent code system (" terminal command ")Copy the code
This tutorial covers everything from basic Python scripts to Web development, crawlers, data analysis, data visualization, machine learning, etc. If you want these materials, you can add the small series of Python learning exchange penguin group: 1075110200, supporting information can find the management sister for free.