preface

The key to learning a language is to stick to it and forget about it. And writing down a passage helps you recall it quickly. The article is divided into two parts, basic Python syntax and object orientation.

Part 1 Basic Python syntax

! [](https://pic3.zhimg.com/80/v2-0ffebab4402a464192d0a82bee64cf1f_720w.png)

Part 1 Basic Python syntax

1. Know the Python

1.1 introduction of Python

Python was founded by Guido van Rossum.

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
Python is a fully object-oriented language, in which everything is an object.

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

There are three ways to run Python programs: interpreter, interactive, and IDE

Python is a very rigidly formatted programming language. Python 2.x does not support Chinese by default.

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
A transitional version, Python 2.6, is officially available to accommodate existing programs.

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
IPython is a Python interactive shell that is much easier to use than the default Python shell. It supports bash shell commands and is suitable for learning/validating Python syntax or local code.

Integrated Development Environment (IDE) — Integrates all the tools needed to develop software, typically including the following tools:

  • Graphical user interface
  • Code editor (code completion/auto indent support)
  • Compiler/interpreter
  • Debugger (breakpoint/step)
! [](https://pic4.zhimg.com/80/v2-f41169a54691afe9d31ff76d32aa2726_720w.png)

PyCharm is a very good integrated development environment for Python

! [](https://pic2.zhimg.com/80/v2-d03849d3795b227cb8e043ca3c4219c7_720w.png)

PyCharm runs the toolbar

1.3. PyCharm setting

The PyCharm configuration information is stored in the.pyCharmXXXX. x directory in the user’s home directory, where xxxx.x represents the version number of PyCharm currently in use

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

To uninstall PyCharm, you only need to do the following two steps:

  • 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
! [](https://pic3.zhimg.com/80/v2-cf06133a55fc3ba596069d89a1030c8e_720w.png)

Makes the selected program executable

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”)

Tip:

  1. More comments are not always better, and you don’t need to add comments for self-explanatory code
  2. For complex operations, several lines of comment should be written before the operation begins
  3. 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)
  4. 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

Is a symbol used to perform basic arithmetic operations, to handle four operations, and “+” and “*” can be used to handle strings.

Operator Description Example + plus 10 + 20 = 30 – minus 10-20 = -10 * x 10 * 20 = 200 / divided by 10/20 = 0.5 // Return the integer part of the division (quotient) 9 // 2 Output result 4% take the remainder Return the remainder of division 9%2 = 1 ** power, also called power, 2 ** 3 = 8

3.2 Comparison (relation) operators

The operator description == checks whether the values of the two operands are equal. If so, the condition is True and returns True! = Check whether the values of the two operands are not equal, if so, return True > Check whether the value of the left operand is greater than the value of the right operand, if so, return True < check whether the value of the left operand is less than the value of the right operand, if so, then the condition is True, Returns True >= Checks whether the value of the left-hand operand is greater than or equal to the value of the right-hand operand, if so, True <= Checks whether the value of the left-hand operand is less than or equal to the value of the right-hand operand, if so, True

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.
Operator Description Example = Simple assignment operator c = a + b Assigns the result of a + b to c += addition assignment operator C += a is equivalent to c = c + a -= subtraction assignment operator C -= a is equivalent to c = c-a *= The multiplication assignment operator C *= a is equivalent to the division assignment operator C = C * A /= the division assignment operator C /= c/A /= the exact division assignment operator C //= a is equivalent to the modular (remainder) assignment operator C %= a Equivalent to c = c % a **= the power assignment operator c **= a is equivalent to c = C ** a

3.4 Identity operators

The identity operator compares the memory location of two objects. There are two common identity operators, described below:

Operator Description Example is Checks whether two identifiers reference the same object X is y, similar to id(x) == ID (y) is not Checks whether two identifiers reference different objects X is not y, similar to id(a)! = id(b)

differentiate

  • 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

The Python member operator tests whether a given value is a member of a sequence. There are two member operators, described as follows:

The operator describing in returns true if the value of a variable is found in the specified sequence, false otherwise. Not in Returns true if the value of the variable cannot be found in the specified sequence, false otherwise.

3.6 Logical operators

And x and y returns True only if both x and y are True


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:
Operator description ** power (highest priority) * / % // Multiply, divide, take remainder, take full division + – addition, subtraction <= < > >= Comparison operator ==! = equal operator = %= /= //= -= += *= **= Assignment operator is is not Identity operator IN NOT IN Member operator not or and Logical operator

< complement > program execution principle

! [](https://pic1.zhimg.com/80/v2-93e234ae89c928653c679a9a9ae857ae_720w.png)

Sketch of Python program execution

  1. The operating system first asks the CPU to copy the Python interpreter’s programs into memory
  2. The Python interpreter tells the CPU to translate the code in a Python program from the top down, based on syntax rules
  3. 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

  1. 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
  1. Use + concatenation strings between string variables
  2. String variables can repeatedly concatenate the same string with an integer using *
  3. 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

Function Description int(x) converts x to an integer float(x) converts x to a floating point number STR (x) converts the object X to a string representation tuple(s) converts s to a tuple list(s) converts s to a list

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
Format character Description %s string %d Is a signed decimal integer. % 06D indicates the number of digits displayed in the output integer. If the number is insufficient, 0 is used to complete the %f floating point number

  • 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

Python includes the following built-in functions:

Function Description Remarks Len (item) counts the number of elements in the container del(item) Deletes the variable del there are two ways Max (item) returns the maximum value of the element in the container if it is a dictionary, compare only for keys min(item) returns the minimum value of the element in the container if it is a dictionary, CMP (item1, item2) compares two values, -1 less than / 0 equal / 1 greater than Python 3.x cancels the CMP function

Note: The string complies with the following rules: “0” < “A” < “A”.

4.4.5.2 slice

Describes the data types supported by Python expression results slice “0123456789”[::-2] “97531” Strings, lists, and tuples

  • 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
Object Oriented Programming – OOP

  • 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

Objects are almost everywhere in Python, and the variables, data, and functions we studied earlier are all objects. There are two ways to verify in Python:

  • 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.
No. Method Name Type Function 01 The __new__ method is automatically called when an object is created. 02 the __init__ method is automatically called when an object is initialized. 03 Before the __del__ method object is destroyed from memory, The 04 __str__ method is automatically called to return the description of the object, and the print function output is used

Tip Using the dir() function saves a lot of learning from rote memorization.

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!
Define a class that contains only methods:

Def method 1(self, argument list): pass def method 2(self, argument list): passCopy the code
The method is defined in much the same format as the functions we learned before, except that the first argument must be self. Note: Class names should be named according to the big camel name. When a class definition is complete, to create an object using that class, the syntax is as follows:

Object variable = class name ()Copy the code
In object-oriented development, the concept of references is equally applicable!
Use print to print an object variable. By default, print which class created the object referenced by the variable and its address in memory (in hexadecimal notation).

Tip: In computers, memory addresses are usually represented in hexadecimal notation.
If you want to print a custom object variable using print during development, you can use the __str__ built-in method:

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

In Python, assigning attributes to objects is very easy, just by passing them through code outside the class. Setting a property is fine, but not recommended:

Def eat(self): print(self) def drink(self): Name = "Tom" print(" Tom") Tom = Cat()#Copy the code
Because: object attributes should be encapsulated inside the class

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

Application scenarios

  • 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
Define the way

  • When defining a property or method, add two underscores to the property or method name to define a private property or method:
! [](https://pic2.zhimg.com/80/v2-e3ad88ac9879369a5e43d9ae0851d7d6_720w.png)

Private properties and private methods

In Python, there is no real private property or method. When you name an attribute or method, you do something special to make it invisible to the outside world: prefix the name with _ class name => _ class name __

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

Three features of object orientation:

  1. Encapsulate properties and methods into an abstract class based on responsibilities
  2. Inheritance enables the reuse of code. The same code does not need to be written repeatedly
  3. 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

The concept of inheritance: a subclass owns a parent class and all properties and methods encapsulated in its parent class.

Class Class name (parent class name): passCopy the code
Override override override override override override override override override override override override override override override override override override override

  1. 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.
  2. 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

A subclass object cannot access its parent’s private properties or methods directly within its own methods. A subclass object can access its parent’s private properties or methods indirectly through its parent’s public methods

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

Subclasses can have more than one parent class and have all the attributes and methods of the parent class. For example, children inherit the characteristics of their parents.

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

Three features of object orientation:

  1. Encapsulation Criteria that define a class by encapsulating properties and methods into an abstract class based on responsibilities
  2. 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
  3. 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!
Case: Encapsulate the method game in the Dog class: ordinary Dog is just a simple play definition. XiaoTianDog inherits from Dog and rewrites the game method: Crouching Dog needs to play in the sky. Define the Person class and encapsulate a method to play with dogs: Inside the method, let the dog object call the Game method directly

! [](https://pic4.zhimg.com/80/v2-5fd4bc422fc95dd21f04fd70d08f4c01_720w.png)

Polymorphic sample

In the Person class, you just have the dog object call the game method, regardless of which dog it is.

Class attributes and class methods

4.1 Class structure

Usually put: The object that you create is called an instance of the class and the action that you take to create it is called instantiating properties of the object is called instance properties and the methods that the object calls are called instance methods and each object has its own memory space that holds its own properties and the methods of multiple objects are only one copy in memory, and when you call a method, A reference to an object needs to be passed inside the method

! [](https://pic3.zhimg.com/80/v2-185db99889ec361fa3dbbd9b506f09bf_720w.png)

Different attributes, unique methods

In Python, a class is a special object.

In Python everything is an object: class AAA: The defined class belongs to the class object obj1 = AAA() belongs to the instance object
When the program is running, the class is also loaded into memory. When the program is running, there is only one copy of a class object in memory, and you can create many instances of an object using a class. In addition to encapsulating the properties and methods of the instance, a class object can also have its own properties and methods — class properties, class methods, by class name. Can access a class’s properties or call a class’s methods

! [](https://pic2.zhimg.com/80/v2-b46468c7475662f93a28dec31c7305a5_720w.png)

The structure of the class

4.2 Class attributes and instance Attributes

Class attributes are attributes defined in a class object that are usually used to record characteristics associated with that class. Class attributes are not used to record characteristics of specific objects. Example: Define a utility class, each tool has its own name.

! [](https://pic1.zhimg.com/80/v2-d452ef763c2ebcd789f39dc6b046177d_720w.png)

Property acquisition mechanism

There is a look-up mechanism for getting attributes in Python

! [](https://pic1.zhimg.com/80/v2-0146d5733379c9891601c9c1463c64fd_720w.png)

Therefore, there are two ways to access class attributes:

  • 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
Syntax is as follows

@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
The sample

  • 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
Syntax is as follows

@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
Example:

  • 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
! [](https://pic1.zhimg.com/80/v2-8d24571745a998538d36ec3865d1a622_720w.png)

Approach:

  • 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
! [](https://pic1.zhimg.com/80/v2-d69dd97043da1602fb2e2ca62cd4691c_720w.png)

! [](https://pic3.zhimg.com/80/v2-b9aeeb240dea4a0c71404f62647ab677_720w.png)

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
! [](https://pic4.zhimg.com/80/v2-d629f237967444252d57293836977814_720w.png)

! [](https://pic1.zhimg.com/80/v2-bf07599406031918907cab274562ee0e_720w.png)

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
demand

  • Let the initialization action be performed only once
The solution

  1. Defines a class attribute, init_flag, to indicate whether an initialization action has been performed, with an initial value of False
  2. In the __init__ method, determine init_flag and initialize if False
  3. Then set init_flag to True
  4. This way, when the __init__ method is called automatically again, the initialization action will not be performed again
! [](https://pic3.zhimg.com/80/v2-88e576b7b9bd1130981bdbcc904e5777_720w.png)

Tips

1. Python can automatically concatenate code inside a pair of parentheses:

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
2. Properties of an object can be objects created by another class. The None keyword means nothing, an empty object with no methods or properties, and is a special constant. None can be assigned to any variable.

When comparing None in Python, it is recommended to use the IS judgment
4. The eval() function is very powerful — evaluates a string as a valid expression and returns the result

! [](https://pic2.zhimg.com/80/v2-891384d94feec4a60b1c1ecf5301e0fc_720w.png)

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.