Your Python Basics Will Be Solid After This Guide!

Follow 👆 the public account and reply "python" to get the zero-based tutorial! Source from the internet, please delete if infringed.
Introduction

Learning a language requires persistence; if you don’t use it, you’ll forget it. Writing an article can also help you quickly recall things in the future. The entire text is divided into two main parts: Python basic syntax and object-oriented programming.

[Tutorial Get it at the end of the article!!]

Tutorial Get it at the end of the article!!

Getting started with Python is actually quite easy, but we need to persist in learning. It’s difficult to stick with it every day; I believe many people give up after a week. Why? It’s actually hard to persist without good learning materials. I hope this helps you.

Part One: Python Basic Syntax

1. Understanding Python

1.1 Introduction to Python

The creator of Python is Guido van Rossum.

The design goals of Python:

A simple and intuitive language that is as powerful as its main competitors and open-source, so anyone can contribute. The code is as easy to understand as plain English and suitable for short-term development of everyday tasks.

The design philosophy of Python:

Elegant, clear, simple.

The philosophy of Python developers is: There should be one—and preferably only one—obvious way to do it.

Python is a fully object-oriented language, where everything is an object.

Scalability: If you need a piece of critical code to run faster or want certain algorithms to remain private, you can write that part in C or C++ and then use it in your Python program.

1.2 Your First Python Program

There are three ways to execute a Python program: using the interpreter, running interactively, or running in an IDE.

Python is a programming language with very strict formatting. Python 2.x does not support Chinese by default.

ASCII characters only include 256 characters and do not support Chinese.

  • The interpreter name for Python 2.x is python.

  • The interpreter name for Python 3.x is python3.

To accommodate existing programs, the official transition version is Python 2.7.

Tip: If you cannot immediately use Python 3.0 during development (as there are still very few third-party libraries that do not support 3.0 syntax), it is recommended to

first develop with Python 3.0, then use Python 2.6 or Python 2.7 for execution, and make some compatibility adjustments.

IPython is an interactive shell for Python that is much more user-friendly than the default Python shell. It supports bash shell commands and is suitable for learning/validating Python syntax or local code.

An Integrated Development Environment (IDE) integrates all the tools needed for software development, generally including the following tools:

  • Graphical User Interface

  • Code Editor (supports code completion/automatic indentation)

  • Compiler/Interpreter

  • Debugger (breakpoints/step execution)

  • ……

Your Python Basics Will Be Solid After This Guide!

PyCharm is an excellent integrated development environment for Python.

Your Python Basics Will Be Solid After This Guide!

PyCharm’s run toolbar

1.4 Practice with Multi-file Projects

  • Developing a project means creating software that is specifically designed to solve a complex business function.

  • Typically, each project has an independent dedicated directory for storing all files related to the project.

  • In PyCharm, to execute a Python program, you must first execute it by right-clicking.

  • For beginners, setting multiple executable programs in one project is very convenient for practicing and testing different knowledge points.

  • For commercial projects, usually only one executable Python source program exists in a project.

Your Python Basics Will Be Solid After This Guide!

Make the selected program executable

2. Comments

  • The purpose of comments is to annotate certain code in a language you are familiar with, enhancing the readability of the program.

2.1 Single-line Comments

  • Start with #, everything after # is treated as explanatory text and is not actual executable code; it serves only as auxiliary explanation.

print(hello python)
# Output hello python

`

To ensure code readability, it is recommended to add a space after # before writing the corresponding explanatory text; to ensure code readability, there should be at least two spaces between comments and code.

2.2 Multi-line Comments

  • To use multi-line comments in a Python program, you can use a pair of consecutive three quotes (either single or double quotes).


This is a multi-line comment

Many, many contents can be written in the multi-line comment...
 
print(hello python)

Tip:

  1. More comments are not better; for self-explanatory code, no comments are needed.

  2. For complex operations, several lines of comments should be written before the operation begins.

  3. For non-obvious code, comments should be added at the end of the line (to improve readability, comments should be at least two spaces away from the code).

  4. Never describe the code; assume the reader knows Python better than you, they just need to know what your code is supposed to do.

2.3 Code Norms:

  • Python officially provides a series of PEP (Python Enhancement Proposals) documents, among which the 8th document specifically gives suggestions on Python’s code format, commonly known as PEP 8: Document Address: https://www.python.org/dev/peps/pep-0008/Google has a corresponding Chinese document: http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/

3. Operators

3.1 Arithmetic Operators

They are symbols used to perform basic arithmetic operations to handle four arithmetic operations, while “+” and “*” can also be used to handle strings.

Operator Description Example + Addition

10 + 20 = 30

– Subtraction

10 - 20 = -10

* Multiplication

10 * 20 = 200

/ Division

 10 / 20 = 0.5

// Floor Division Returns the integer part of the division (quotient)

 9 // 2 Output
4

% Modulus Returns the remainder of the division

 9 % 2 = 1 
** Power Also known as exponentiation,

2 ** 3 = 8

3.2 Comparison (Relational) Operators

Operator Description

== Checks if the values of the two operands are equal. If so, the condition holds true, returning True.

!= Checks if the values of the two operands are not equal. If so, the condition holds true, returning True.

> Checks if the left operand’s value is greater than the right operand’s value. If so, the condition holds true, returning True.

< Checks if the left operand’s value is less than the right operand’s value. If so, the condition holds true, returning True.

>= Checks if the left operand’s value is greater than or equal to the right operand’s value. If so, the condition holds true, returning True.

<= Checks if the left operand’s value is less than or equal to the right operand’s value. If so, the condition holds true, returning True.

In Python 2.x, the not equal judgment can also use the <> operator.

!= can also be used to judge not equal in Python 2.x.

3.3 Assignment Operators

  • In Python, the = operator can assign values to variables.

  • In arithmetic operations, Python also provides a series of assignment operators corresponding to arithmetic operators. Note: Assignment operators cannot use spaces in between.

Operator Description Example = Simple assignment operator

 c = a + b
# Assign the result of a + b to c   
+= Addition assignment operator

c += a 
# Equivalent to c = c + a 

-= Subtraction assignment operator

c -= a 
# Equivalent to c = c - a

*= Multiplication assignment operator

c *= a 
# Equivalent to c = c * a

/= Division assignment operator

c /= a 
# Equivalent to c = c / a 

//= Floor division assignment operator

c //= a 
# Equivalent to c = c // a

%= Modulus (remainder) assignment operator

c %= a 
# Equivalent to c = c % a 

**= Power assignment operator

c **= a 
# Equivalent to c = c ** a

3.4 Identity Operators

Identity operators compare the memory location of two objects. The commonly used identity operators are as follows:

Operator Description Example

is Determines whether two identifiers reference the same object x is y, similar to id(x) == id(y) is.

not Determines whether two identifiers reference different objects x is not y, similar to id(a) != id(b).

Distinction

  • is is used to determine whether the two variables reference the same object.

  • == is used to determine whether the values of the referenced variables are equal.

3.5 Membership Operators

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

Operator Description

in Returns true if a variable’s value is found in the specified sequence; otherwise, it returns false.

not in Returns true if a variable’s value is not found in the specified sequence; otherwise, it returns false.

3.6 Logical Operators

Operator Logical Expression Description

and x and y Returns True only if both x and y are True; otherwise, if either x or y is False, it returns False.

or x or y Returns True if either x or y is True; it only returns False if both x and y are False.

not not x Returns False if x is True; returns True if x is False.

3.7 Operator Precedence

  • The following table lists arithmetic precedence from highest to lowest:

Operator Description

** Exponentiation (highest precedence)

* / % // Multiplication, division, modulus, floor division

+ – Addition, subtraction

<= < > >= Comparison operators

== != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

<Supplement> Program Execution Principle

Your Python Basics Will Be Solid After This Guide!

Illustration of Python program execution

  1. The operating system first lets the CPU copy the Python interpreter program into memory.

  2. The Python interpreter translates the code in the Python program according to syntax rules, from top to bottom.

  3. The CPU is responsible for executing the translated code.

How large is the Python interpreter?

  • You can check the size of the Python interpreter by executing the following terminal commands

# 1. Confirm the location of the interpreter $ which python # 2. Check the size of the python file (just a soft link) $ ls -lh /usr/bin/python # 3. View the specific file size $ ls -lh /usr/bin/python2.7

4. Variables

4.1 Variable Definition

  • In Python, every variable must be assigned a value before use. A variable is created only after it is assigned a value.

  • You can define a variable using the result of other variables’ calculations.

  • The variable name is only defined the first time it appears.

Variable Name = Value

Using an interactive way, if you want to view the contents of a variable, simply enter the variable name; there is no need to use the print function. To output the content of a variable using the interpreter, you must use the print function.

4.2 Variable Types

  • In Python, defining variables does not require specifying types (which is required in many other high-level languages). Python can automatically infer the type of data stored in a variable based on the value on the right side of the = sign.

  • Data types can be divided into numeric and non-numeric. Numeric types include integer (int): All integers in Python 3 are represented as long integers. Therefore, long integers do not have a separate numeric type. Floating-point type (float) Boolean type (bool): True for non-zero numbers, False for 0. Complex type (complex): A complex number is represented as an ordered pair of real floating-point numbers x + yj, where x and y are real numbers and j is the imaginary unit. Non-numeric types: Some operators also support these data types; see 4.4.5.3 Operators.

  • String (str): The plus (+) is the string concatenation operator, while the asterisk (*) is the repetition operator.

  • List (list) Tuple (tuple) Dictionary (dict)

Tip: In Python 2.x, integers are further divided based on the length of the value stored:

int (integer) long (long integer)

  • You can use the type function to view the type of a variable.

In [1]: type(name)

<Supplement> Calculations Between Different Types of Variables
  1. Numeric variables can be directly calculated.

  • In Python, two numeric variables can perform arithmetic operations directly.

  • If the variable is of type bool, during calculations, True corresponds to the number 1, and False corresponds to the number 0.

  1. String variables can be concatenated using +.

  2. String variables can use * to repeat the same string with an integer.

  3. Numeric variables and string variables cannot perform other calculations.

<Supplement> Getting Input from the Keyboard: input
  • You can use the input function in Python to wait for user input from the keyboard.

  • Any content entered by the user is considered a string by Python.

String variable = input(prompt:)

<Supplement> Type Conversion Functions

Function Description int(x) Converts x to an integer float(x) Converts x to a floating-point number str(x) Converts object x to string representation tuple(s) Converts s to a tuple list(s) Converts s to a list

price = float(input(Please enter price:))

<Supplement> Formatted Output: print
  • If you want to output text information along with data, you need to use the formatting operator.

  • % is known as the formatting operator, specifically used for handling formats in strings. Strings containing % are called formatted strings. When combined with different characters, different types of data require different formatting characters.

Formatting characters Meaning %s String %d Signed decimal integer, %06d indicates the number of digits to display for the integer, with 0 padding for insufficient places %f Floating point number, %.2f indicates only two decimal places % Output %

  • The syntax format is as follows:

print(formatted string % variable1)

print(formatted string % (variable1, variable2…))

4.4.5 Common Methods and Advanced Applications of 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 a container

del(item) Deletes a variable

max(item) Returns the maximum value among the elements in a container. If it is a dictionary, it only compares keys.

min(item) Returns the minimum value among the elements in a container. If it is a dictionary, it only compares keys.

cmp(item1, item2) Compares two values, -1 is less than / 0 is equal / 1 is greater. Python 3.x has removed the cmp function.

Note: String comparisons follow the rules: 0 < A < a.

4.4.5.2 Slicing

Describes Python expressions Results Supported data types Slicing 0123456789[::-2] 97531 String, list, tuple

  • Slicing uses index values to limit the range, cutting out a smaller string from a larger string.

  • Lists and tuples are both ordered collections that can access the corresponding data via index values.

  • Dictionaries are unordered collections that store data using key-value pairs.

Object-Oriented Programming (OOP)

  • Procedural-oriented: How to do it? Implement all steps to meet a requirement sequentially. Based on development requirements, encapsulate independent code functionality into functions to complete the code, which is then called sequentially. Characteristics: Focus on steps and processes, not on roles. If the requirement is complex, the code will become very complicated. Developing complex projects has no fixed routine and is very difficult!

  • Object-oriented: Who does it? Compared to functions, object-oriented programming is a larger encapsulation. Multiple methods are encapsulated in one object based on roles. Before completing a requirement, determine the role—what needs to be done (method). Determine different objects based on roles, encapsulating different methods (multiple) within the object. The final code is executed by sequentially calling different objects.

  • Different methods Characteristics: Focus on objects and roles; different objects assume different responsibilities, making it more suitable for handling complex requirement changes. It is designed to address complex project development, providing fixed routines. You need to learn some object-oriented syntax based on procedural programming.

  • Classes and Objects A class is a general term for a group of things that have the same characteristics or behaviors. It is abstract, with characteristics known as attributes and behaviors known as methods. An object is a specific existence created by a class, which is an instance of the class. In program development, to design a class, typically three elements must be satisfied: Class Name—the name of the class of things, which must follow PascalCase. Attributes—what characteristics this class of things has. Methods—what behaviors this class of things has.

2. Basic Syntax of Object-Oriented Programming

2.1 dir Built-in Function and Built-in Methods

In Python, objects are almost ubiquitous. The variables, data, and functions we learned before are all objects. You can verify this in Python using the following two methods:

  • After entering a dot . after an identifier/data, pressing the TAB key will prompt a list of methods that the object can call.

  • Using the built-in function dir passing in an identifier/data allows you to view all attributes and methods within the object. Note that methods in the format __method_name__ are built-in methods/attributes provided by Python.

Method Name Type Function __new__ Method is automatically called when creating an object. __init__ Method is automatically called when an object is initialized. __del__ Method is automatically called before an object is destroyed from memory. __str__ Method returns the description of the object, used for output with the print function.

Tip: Utilize the dir() function well, and many contents don’t need to be memorized.

2.2 Defining a Simple Class (Only Contains Methods)

Object-oriented programming is a larger encapsulation. In a class, multiple methods are encapsulated, allowing objects created from this class to directly call these methods!

Defining a class that only contains methods:

class ClassName:

   def method1(self, parameter_list):
       pass

   def method2(self, parameter_list):
       pass

The definition format of a method is almost the same as that of a function learned previously, except that the first parameter must be self. Note: The naming rule for class names must follow PascalCase. After defining a class, to create an object using this class, the syntax format is as follows:

Object Variable = ClassName()

In object-oriented development, the concept of references is also applicable!

Using print to output the object variable, by default, it can output which class the variable reference object was created from and its address in memory (in hexadecimal representation).

Tip: In computers, memory addresses are typically represented in hexadecimal.

If, during development, you want to print custom content when outputting the object variable, you can use the built-in method __str__:

class Cat:

   def __init__(self, new_name):
       self.name = new_name
       print(%s came % self.name)  

   def __del__(self):
       print(%s left % self.name)    

   def __str__(self):
       return I am a kitten: %s % self.name

tom = Cat(Tom)
print(tom)

Note: The __str__ method must return a string.

2.3 The self Parameter in Methods

In Python, setting attributes for an object is very easy; you just need to directly set an attribute through object. However, this is not recommended:

class Cat:   This is a cat class
   def eat(self):       print(Kittens love fish)       def drink(self):       print(Kittens are drinking water)
tom = Cat()# Set attribute for the object tom.name = Tom

Because: The encapsulation of object attributes should be done within the class.

Whichever object calls the method, self in the method is a reference to that object.

  • Within the methods encapsulated in a class, self represents the object that calls the current method itself. Within the method, you can access the object’s attributes through self. and call other methods of the object via self.

  • When calling a method, the programmer does not need to pass the self parameter.

  • Outside the class, you can access the object’s attributes and methods via variable name. Inside the methods encapsulated in the class, you can access the object’s attributes and methods through self.

2.4 Initialization Method: __init__

  • When creating an object using ClassName(), the following operations are automatically performed: Allocate space for the object in memory— Create the object and set initial values for the object’s attributes— Initialization method (__init__).

The __init__ method is specifically used to define what attributes a class has!

  • In the __init__ method, use self.attribute_name = initial_value to define attributes. After defining attributes, any object created using the class will have those attributes.

  • If you want to set the object’s attributes at the same time as creating the object, you can modify the __init__ method: define the attribute values you want to set as parameters in the __init__ method. Inside the method, use self.attribute = parameter to receive externally passed parameters. When creating the object, use ClassName(attribute1, attribute2…) to call.

class Cat:
   This is a cat class

   def eat(self):
       print(Kittens love fish)    def drink(self):
       print(Kittens are drinking water)

tom = Cat()
# Set attribute for the object
tom.name = Tom

2.5 Private Attributes and Methods

Application Scenarios

  • In actual development, some attributes or methods of an object may only be intended for internal use and should not be accessed externally.

  • Private attributes are attributes that the object does not wish to expose.

  • Private methods are methods that the object does not wish to expose.

Definition Method

  • When defining attributes or methods, adding two underscores before the attribute name or method name defines a private attribute or method:

Your Python Basics Will Be Solid After This Guide!

Private attributes and private methods

Pseudo-private attributes and private methods: In Python, there is no true meaning of private. When naming attributes and methods, it actually performs some special processing on the name to make it inaccessible from the outside: by adding _class_name => _class_name__name.

# Private attribute, cannot be accessed directly from outside
print(xiaofang._Women__age)

# Private method, cannot be called directly from outside
xiaofang._Women__secret()

Tip: In daily development, do not use this method to access the object’s private attributes or methods.

3. Encapsulation, Inheritance, and Polymorphism

The three major characteristics of object-oriented programming:

  1. Encapsulation encapsulates attributes and methods into an abstract class based on roles.

  2. Inheritance achieves code reuse; the same code does not need to be rewritten.

  3. Polymorphism allows different objects to call the same method and produce different execution results, increasing code flexibility.

3.1 Inheritance

3.1.1 Single Inheritance

The concept of inheritance: a subclass has all the attributes and methods encapsulated in its parent class and its parent’s parent class.

class ClassName(ParentClassName):

   pass

When the implementation of a method in the parent class cannot meet the subclass’s needs, the method can be overridden. Overriding the parent class method can occur in two scenarios:

  1. Replacing the parent class method: The implementation of the parent class method is completely different from the implementation in the subclass. The specific implementation method is equivalent to defining a method with the same name in the subclass and implementing it.

  2. Extending the parent class method: The implementation of the subclass method contains the implementation of the parent class method. In the subclass, override the parent class method; at the necessary positions, use super().parent_method to call the execution code of the parent class method; at other positions, write the code implementation specific to the subclass’s needs.

About super
  • In Python, super is a special class.

  • super() creates an object using the super class.

  • The most commonly used scenario is when overriding the parent class method, calling the method encapsulated in the parent class.

Another way to call the parent class method: In Python 2.x, if you need to call the parent class method, you can also use the following method: ParentClassName.method(self). This method is still supported in Python 3.x, but it is not recommended because if the parent class changes, the class name at the method call location also needs to be modified.

Private attributes and methods of the parent class

Subclass objects cannot directly access the private attributes or private methods of the parent class within their own methods. Subclass objects can indirectly access private attributes or methods through the public methods of the parent class.

Private attributes and methods are the privacy of the object and are not publicly disclosed. The outside world and subclasses cannot directly access private attributes and methods, which are usually used for internal matters.

3.1.2 Multiple Inheritance

A subclass can have multiple parent classes and possess all attributes and methods of its parent classes. For example: a child inherits characteristics from both its father and mother.

class SubClassName(ParentClassName1, ParentClassName2...):
   pass

Python’s MRO Algorithm (Method Resolution Order)
  • If there are methods with the same name in different parent classes, which parent’s method will be called when a subclass object calls the method? Tip: During development, try to avoid situations that can easily cause confusion!— If there are attributes or methods with the same name between parent classes, it is best to avoid using multiple inheritance.

  • Python provides a built-in attribute __mro__ to view the method search order. When searching for a method, it searches in the order of the output of mro from left to right. If the method is found in the current class, it executes directly without further searching. If it is not found, it checks the next class for the corresponding method. If found, it executes directly without further searching. If the last class is reached and the method is still not found, the program will report an error.

MRO is method resolution order— it mainly determines the method and attribute calling path in multiple inheritance.

New-style classes vs Old-style (Classic) classes
  • New-style classes: Classes that use object as the base class, recommended for use.

  • Classic classes: Classes that do not use object as the base class, not recommended for use.

In Python 3.x, when defining a class without specifying a parent class, it will default to using object as the base class— all classes defined in Python 3.x are new-style classes. In Python 2.x, when defining a class without specifying a parent class, it will not use object as the base class.

  • To ensure that the written code can run in both Python 2.x and Python 3.x, it is recommended to uniformly inherit from object when defining classes in the future if there is no parent class:

class ClassName(object):
   pass

object is the base class provided by Python for all objects, providing some built-in attributes and methods that can be viewed using the dir(object) function.

3.2 Polymorphism

The three major characteristics of object-oriented programming:

  1. Encapsulation Encapsulates attributes and methods into an abstract class based on roles, defining class criteria.

  2. Inheritance Achieves code reuse; the same code does not need to be rewritten, designing class techniques. Subclasses write specific code for their unique needs.

  3. Polymorphism Different subclass objects call the same parent class method, producing different execution results, increasing code flexibility. This requires calling methods based on inheritance and overriding parent class methods without affecting the internal design of the class.

Polymorphism makes it easier to write general code and create general programming to adapt to the ever-changing requirements!

Example: In the Dog class, encapsulate the method game: ordinary dogs just play. Define XiaoTianDog inheriting from Dog and override game method: the celestial dog needs to play in the sky. Define a Person class and encapsulate a method to play with dogs: internally, directly let the dog object call the game method.

Your Python Basics Will Be Solid After This Guide!

Example of polymorphism

In the Person class, you only need to let the dog object call the game method without caring about what kind of dog it is.

4. Class Attributes and Class Methods

4.1 Class Structure

Typically, the created objects are called class instances, and the action of creating objects is called instantiation. The attributes of an object are called instance attributes, and the methods invoked by the object are called instance methods. Each object has its own independent memory space to store different attributes, while multiple objects share only one copy of the methods. When calling a method, the object’s reference is passed to the method.

Your Python Basics Will Be Solid After This Guide!

Different attributes, one copy of methods

In Python, a class is a special object.

Everything is an object in Python:

class AAA: The defined class is a class object obj1 = AAA() belongs to instance object.

During program execution, classes are also loaded into memory. During program execution, there is only one copy of the class object in memory, and many object instances can be created from one class. In addition to encapsulating instance attributes and methods, class objects can also have their own attributes and methods—class attributes and class methods, which can be accessed or called using ClassName.

Your Python Basics Will Be Solid After This Guide!

Class Structure

4.2 Class Attributes and Instance Attributes

Class attributes are attributes defined in the class object. They are usually used to record characteristics related to the class. Class attributes are not used to record specific object characteristics.Example: Define a tool class, each tool has its own name: Requirement— Know how many tool objects have been created using this class?

Your Python Basics Will Be Solid After This Guide!

Attribute Acquisition Mechanism

In Python, there is an upward search mechanism for acquiring attributes.

Your Python Basics Will Be Solid After This Guide!

Therefore, there are two ways to access class attributes:

  • ClassName.class_attribute

  • Object.class_attribute (Not recommended, because if you use Object.class_attribute = value assignment statement, it will only add an attribute to the object and will not affect the value of the class attribute).

4.3 Class Methods and Static Methods

4.3.1 Class Methods

  • Class attributes are defined for class objects. Use assignment statements under the class keyword to define class attributes. Class attributes are used to record characteristics related to this class.

  • Class methods are methods defined for class objects. Within class methods, you can directly access class attributes or call other class methods.

The syntax is as follows:

@classmethod
def class_method_name(cls):
   pass

  • Class methods need to be marked with the decorator @classmethod to inform the interpreter that this is a class method.

  • The first parameter of a class method should be cls, which refers to the class that calls the method. Inside the method, cls is the reference to that class. This parameter is similar to the self parameter of instance methods. Tip: You can use other names, but it is customary to use cls.

  • You can call a class method using ClassName. You do not need to pass the cls parameter when calling the method.

  • Inside the method, you can access the class’s attributes through cls. and also call other class methods through cls.

Example:

  • Define a tool class, each tool has its own name.

  • Requirement— Encapsulate a class method show_tool_count to output the number of objects created using the current class.

@classmethod
def show_tool_count(cls):
   Display the total number of tool objects
   print(Total number of tools: %d % cls.count)

4.3.2 Static Methods

  • If you need to encapsulate a method in a class that:
  • Does not need to access instance attributes or call instance methods, and also does not need to access class attributes or call class methods.

  • In this case, you can encapsulate this method as a static method.

The syntax is as follows:

@staticmethod
def static_method_name():
   pass

  • Static methods need to be marked with the decorator @staticmethod to inform the interpreter that this is a static method.

  • You can call a static method using ClassName.

Example:

  • The static method show_help displays game help information.

  • The class method show_top_score displays the highest score.

  • The instance method start_game starts the current player’s game.

Your Python Basics Will Be Solid After This Guide!

Exploration:

  • Instance Methods — Methods that need to access instance attributes. Instance methods can use ClassName. to access class attributes.

  • Class Methods — Methods that only need to access class attributes.

  • Static Methods — Methods that do not need to access instance attributes and class attributes.

5. Singleton

5.1 Singleton Design Pattern

  • The design pattern is a summary and refinement of previous work. Typically, widely circulated design patterns are mature solutions to specific problems. Using design patterns is to reuse code, make code easier for others to understand, and ensure code reliability.

  • The purpose of the singleton design pattern is to ensure that the object created by a class has only one instance in the system. Each time you execute ClassName(), the returned object’s memory address is the same.

  • Application scenarios for the singleton design pattern include music players, recycle bin objects, printer objects, etc.

5.2 Static Method: __new__

  • When creating an object using ClassName(), 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, mainly serving two purposes: allocating space for the object in memory and returning the object’s reference.

  • After obtaining the object’s reference, the Python interpreter passes this reference as the first parameter 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 get the reference of the allocated object, and the object’s initialization method will not be called.

  • Note: __new__ is a static method, and you need to actively pass the cls parameter when calling it.

Your Python Basics Will Be Solid After This Guide!

Your Python Basics Will Be Solid After This Guide!

5.3 Singleton in Python

  • A singleton ensures that the object created by a class has only one instance in the system. Define a class attribute with an initial value of None to record the reference of the singleton object. Override the __new__ method. If the class attribute is None, call the parent class method to allocate space and record the result in the class attribute, returning the object reference recorded in the class attribute.

Your Python Basics Will Be Solid After This Guide!

Your Python Basics Will Be Solid After This Guide!

Only execute initialization work once

  • Each time you create an object using ClassName(), the Python interpreter automatically calls two methods: __new__ to allocate space and __init__ to initialize the object.

  • After modifying the __new__ method, you will always get the reference of the first created object.

  • However, the initialization method will still be called again.

Requirement:

  • Ensure that the initialization action is only executed once.

Solution:

  1. Define a class attribute init_flag to mark whether the initialization action has been executed, with an initial value of False.

  2. In the __init__ method, check init_flag; if it is False, execute the initialization action.

  3. Then set init_flag to True.

  4. This way, when __init__ is automatically called again, the initialization action will not be executed again.

Your Python Basics Will Be Solid After This Guide!

Tips

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

'''
**Requirement**

* Define the `input_password` function to prompt the user to input a password
* If the user inputs a length < 8, throw an exception
* If the user inputs a length >=8, return the input password
'''
def input_password():

   # 1. Prompt the user to input a password
   pwd = input(Please enter password:)    
   # 2. Check the length of the password; if the length >= 8, return the user input password
   if len(pwd) >= 8:        return pwd    
   # 3. Password length is insufficient; an exception needs to be thrown
   # 1> Create an exception object - use the error message string of the exception as a parameter
   ex = Exception(Password length insufficient)    
   # 2> Throw the exception object
   raise extry:
   user_pwd = input_password()
   print(user_pwd)except Exception as result:
   print(Error found: %s % result)

2. An object’s attribute can be another object created by another class. 3. When defining class attributes in the __init__ method, if you don’t know what initial value to set, you can set it to None: The None keyword indicates nothing, representing an empty object, which has no methods and attributes and is a special constant. You can assign None to any variable.

When comparing with None in Python, it is recommended to use is for comparison.

4. The eval() function is very powerful—it evaluates a string as a valid expression and returns the computed result.

Your Python Basics Will Be Solid After This Guide!

  • During development, never use eval to directly convert the result of input, for example:

  • __import__('os').system('ls')
    
    # Equivalent code import osos.system(terminal command)
    

How to get:

  1. Like + View Again

  2. Reply “python” in the public account

Get the latest Python zero-based learning materials for 2025,Reply in the background:Python

Leave a Comment