object-oriented
Two core concepts are classes and objects
Class is a template
Object is an instance created according to this template
Relationship between classes and objects
Classes are templates, and objects are created based on this template
There should be classes before objects
There is only one class, and there can be multiple objects
The properties of different objects may be different
There can be neither more nor less attributes and methods defined in the class nor in the object
To design a class, you usually need to meet
- Class name: big hump nomenclature initial capital
- Attribute: what are the characteristics of such things
- Method: what kind of behavior does this kind of thing have
Determination of properties and methods
- Feature description of objects: usually defined as attributes
- The behavior of an object (verb): usually defined as a method
Three characteristics of object oriented
- Encapsulation: encapsulation encapsulates attributes and methods into an abstract class according to responsibilities
- Inheritance: inheritance realizes code reuse. The same code does not need to be written repeatedly
- Polymorphism: different objects call the same method to produce different execution results, increasing the flexibility of the code
Object oriented basic syntax
In python, everything is an object. Variables, functions and data are objects
encapsulation
concept
Generalized encapsulation: the definition of functions and the extraction of classes are the embodiment of encapsulation.
Narrow encapsulation: in object-oriented programming, some attributes of a class can be encapsulated if they do not want to be directly accessed by the outside world (privatize the attributes that do not want to be directly accessed by the outside world, which can only be held by the current class. At this time, an accessed function can be exposed to the outside world).
The essence of encapsulation: it is the process of attribute privatization.
Advantages of encapsulation: it improves the security and reusability of data.
dir built-in function
Use dir (object name) to view all properties and methods in an object
With ___ The method name of is the method or property provided by python for the object
After the object is created in python, the address of the object in memory is still recorded in the object variable
print is used to output the object variable. By default, the object referenced by this variable can be output by which class is created
And the address in memory (in hexadecimal)
In computers, hexadecimal is usually used to represent the memory address
%d outputs digits in decimal
%x outputs numbers in hexadecimal
You can directly add attributes to the object outside the class. This method is not recommended and should be encapsulated internally
class Cat: def eat(self): print("Kittens love fish") def drink(self): print("Kittens like to drink water") # Create cat object tom = Cat() tom.name = "Tom" # Here, add the name attribute to tom directly outside the class
self attribute
When defining a method in a class, you must have the self attribute
For the method called by which object, the self inside the method is the reference of which object (self is the reference of the instance object)
Within the class encapsulated method, self represents the object of the current calling method itself.
Initialization method init
When you create an object using the class name (), the following actions are performed automatically
1. Allocate space for objects in memory – create objects
2. Set the initial value for the attribute of the object -- initialization method #init
init is a built-in method for an object
Init method is specially used to define which attributes a class has
It will be called automatically when the object is created
In development, if you want to set the properties of the object while creating the object, you can modify the init method
- Define the parameter called init method for the attribute value you want to set
- Use self. Inside the method Attribute = formal parameter receives external passed parameters
- . When an object is created, it is called with the class name (property 1, property 2)
# example class Cat(): def __init__(self, new_name): # The formal parameter new is set here_ Name is convenient to receive external parameters print("This is the initialization method") # self.name = "Tom" self.name = new_name def eat(self): print("%s I like fish" % self.name) tom = Cat("Tom") # When you create an object, you pass in parameters print(tom.name) tom.eat() lazy_cat = Cat("Big lazy cat") lazy_cat.eat()
Two built-in methods
- del
- str
① The built-in method del method opposite to the initialization method
In python, when an object is created with the class name (), the init method is automatically called after allocating play space for the object
When an object is destroyed from memory, the del method is automatically called
If you want to do something more before the object is destroyed, you can use the del method
life cycle
An object is created by calling the class name () and its life cycle begins
Once the del method of an object is called, the life cycle ends
During the object's declaration cycle, you can access object properties or have the object call methods
② str method
In python, print is used to output object variables,
By default, it will output which class the object referenced by this variable is created by and the address in memory (hexadecimal)
If you want to print custom content when printing object variables during development, you can use the str built-in method
The str method must return a string
class Cat: def __init__(self, new_name): #Initialization method automatically called after object creation self.name = new_name print("%s coming" % self.name) def __del__(self): # Used when you want to do something before the object is destroyed print("%s I went" % self.name) def __str__(self): # Used when you want print(tom) to return custom content # You must return a string return "I'm a kitten[%s]" % self.name tom = Cat("Tom") print(tom)
Private properties and private methods
In actual development, some properties or methods of an object may only be used inside the object rather than being accessed externally
At this point, you can define private properties and private methods
Double underline defined attributes__ that will do
In fact, in python, there is no real private property, but special treatment
In fact, some special processing is done on the name, so that the outside world can't access it
The processing method is as follows: add before the name_ Class name_ Class name__ name
Is to add an underscore before the attribute or method and the name of the class that created them
Subclass objects cannot directly access private properties or private methods of the parent class
However, subclass objects can indirectly access the private properties and methods of the parent class through the public methods of the parent class
inherit
Inheritance: a subclass has all the methods and properties of its parent class
class Class name(Parent class name): pass
Inheritance is transitive: subclasses have the properties and methods of the parent class and the parent class of the parent class
When the method implementation of the parent class cannot meet the needs of the child class, the method can be overridden
Method override
1. Override parent method
Just redefine the method in the subclass
2. Extend parent class methods
① Override parent method in subclass
② Use super() in the appropriate position Parent method
The isinstance(object, Cat) function is used to determine whether an instance is created by a class to determine whether the object is the parent class of Cat
Judge whether it is its subclass issubclass (dog, animal) > > true
Call the superclass Method Super (cat, self) eat()
Multiple inheritance
In python, a subclass can have multiple parent classes, and the properties and methods of multiple parent classes are called multiple inheritance
class C (A, B): pass
Precautions for using multiple inheritance
If there are identical methods or properties in different parent classes, you should try to avoid using multiple inheritance
MRO in python -- method search order
python provides a built-in property for classes__ mro__, You can view the method search order
MRO is a method resolution order, which is mainly used to judge the call path of methods and properties during multi inheritance
print(C.__mro__)
New type and old (Classic) type
New class: a class based on object
Classic class: a class that does not take object as the base class
polymorphic
Polymorphism: different subclass objects call the same parent method to produce different execution results
Polymorphism can improve the flexibility of layered code
On the premise of inheriting and overriding parent class methods
It is the skill of calling methods and will not affect the internal design of the class
Terminology - Examples
In object-oriented development, the first step is to design classes
Create an object using the class name (). There are two steps to create an object
1. Allocate space for objects in memory
2. Call the initialization method init to initialize the object
After the object is created, there is an object instance in memory
Usually
1. The created object is called an instance of a class
2. The act of creating an object is called instantiation
3. The properties of an object are called instance properties
4. The method called by an object is called an instance method
Example method
Class is a special object
In python, everything is an object
class AAA: the defined class belongs to class object
aaa = AAA(): the object created through the class belongs to the instance object
When the program runs, the class will also be loaded into memory, and the class object has only one copy in memory.
Class objects can also have their own properties and methods called class properties and class methods
Class method
Class attribute: refers to the attribute defined for the class object. Class attribute is used to record the relevant characteristics of this class
Class methods: methods defined for class objects
Class methods are defined as follows
@classmethod def Class method name(cls): pass
Class methods need to be identified by the modifier @ classmethod to tell the interpreter that this is a class method
The first parameter of a class method should be cls, which is similar to the self parameter of an instance method
Static method
During development, if you need to encapsulate a method in a class
This method does not need to access instance properties or call instance methods
There is no need to access class properties or call class methods
At this time, you can encapsulate this method into a static method
The syntax is as follows
@staticmethod def Static method name(): pass
Static methods do not access class properties, instance properties, class methods, and instance methods
Static methods do not need to create objects and use class names directly Static method call
class Dog(object): @staticmethod def run(): # No parameters need to be passed # Do not access instance properties or class properties print("Dog, run...") # By class name To call static methods -- you don't need to create objects Dog.run()
The instance attribute is defined in the init method
Class properties are defined directly in the class
Comprehensive examples of three methods
class Game(object): # Class attribute history highest score top_score = 0 # The instance attribute is defined in the init method def __init__(self, player_name): self.player_name = player_name # Static method to display game help @staticmethod def show_help(): print("Help message: let zombies enter the gate") # Class method to display the highest score of the game @classmethod def show_top_score(cls): print("Historical records %d" % cls.top_score) # Instance method to start the game def start_game(self): print("%s Start the game..." % self.player_name) # 1. View game help information Game.show_help() # 2. View the highest score in history Game.show_top_score() # 3. Create game objects game = Game("Xiao Ming") game.start_game()
1. When the instance attribute needs to be accessed inside the method, it is defined as ----- instance method
Class names can be used inside instance methods Access class properties
2. When only class attributes need to be accessed inside the method, it is defined as ----- class method @ classmethod
3. When neither strength attribute nor class attribute needs to be accessed inside the method, it is defined as ----- static method @ staticmethod
If you need to access both instance properties and class properties inside the method
It should be defined as an instance method, because there is only one class, and the class name can be used in the instance method Access class properties
Singleton design pattern
Design pattern
1. Design patterns are the summary and refinement of previous work. Generally, the widely circulated design patterns are mature solutions to a specific problem
2. The purpose of using design patterns is to reuse code, make code easier to be understood by others, and ensure code reliability
Singleton design pattern
1. Purpose - let the object created by the class have only one instance in the system
2. The memory address of the object created by the class name () is the same every time
Application scenario of singleton design pattern
1. Music player object
2. Recycle bin object
3. Printer object
Is the only existing object in the system
Built in method new method
In python, when you create an object using the class name (), the python interpreter calls__ new__ Method to allocate space for the object
__ new__ It is a built-in static method provided by the object base class. It has two main functions
1. Allocate space for objects in memory
2. Return reference to object
After obtaining the reference of the object, the python interpreter passes the reference as the first parameter to the init method
In python, when you create an object using the class name (), you call__ new__ Method allocates space for the object before the initialization operation is performed
To implement the singleton pattern, you need to rewrite the new method, which is very fixed
If you override the new method, you must return super()__ new__ (CLS), otherwise the python interpreter will not execute the initialization method if it cannot get the object reference allocated space
Note: the new method is a static method, which needs to actively pass in the cls parameter when calling
__ new__ The method is simple to use
# __ new__ The method is simple to use class MusicPlayer(object): def __new__(cls, *args, **kwargs): # 1. When creating an object, the new method will be called automatically print("Create objects and allocate space") # 2. Allocate space for objects instance = super().__new__(cls) # 3. If there is no return, the initialization method will not be executed return instance def __init__(self): print("Player initialization") player = MusicPlayer() print(player)
__ new__ Method is rewritten to implement the singleton pattern
# __ new__ Method is rewritten to implement the singleton pattern class MusicPlayer(object): # Record the reference of the first object created instance = None init_flag = False # Here, in order to make the initialization method execute only once, a parameter flag is set def __new__(cls, *args, **kwargs): # 1. Judge whether the class attribute is an empty object if cls.instance is None: # 2. Call the parent class method to allocate space for the first object cls.instance = super().__new__(cls) # 3. Return the object reference saved by the class attribute return cls.instance def __init__(self): # Determine whether the initialization method has been executed if MusicPlayer.init_flag: return # If not, execute the initialization method print("Initialize player") # Modify class attribute tag MusicPlayer.init_flag = True # Create multiple objects player1 = MusicPlayer() # The memory address of each object is different before overriding the new method print(player1) player2 = MusicPlayer() # After overriding the new method, each object with the same memory address is the same object print(player2)
abnormal
When the program is running, if the python interpreter encounters an error, it will stop the execution of the program and prompt some error messages, which is an exception (this error message is prompted to the programmer, but the user can't see it, so he can only see the stop operation)
The action that the program stops executing and prompts an error message is called throwing an exception
Catch exception complete code
# Catch exception complete code try: num = int(input("Please enter an integer:")) result = 8/num print(result) except ValueError: print("Please enter the correct integer") except Exception as e: print("unknown error %s " % e) # else is executed when no exception occurs else: print("No exception occurred") # finally, the following code will be executed regardless of whether there are exceptions or not finally: print("Code that executes regardless of whether an exception occurs")
Actively throw exception
In development, except for exceptions thrown by the python interpreter after code execution errors
You can also actively throw exceptions according to the unique business requirements of the application
Active exception throwing syntax
1. Create an exception object
2. Use the raise keyword to throw an exception object
# Actively throw exception def input_password(): # 1. Prompt the user to enter the password pwd = input("Please input a password:") # 2. Judge the password length > = 8 and return the password entered by the user if len(pwd) >= 8: return pwd # 3. If < 8, throw an exception actively print("Actively throw exception") # 1> Create exception object ex = Exception("The password is not long enough") # 2> Actively throw exception raise ex # After actively throwing an exception, you can also catch the thrown exception try: print(input_password()) except Exception as e: print("unknown error%s" % e)
Module import
Each independent py file is a module that can be imported
1,import
2,from ... import ...
If you want to import some tools from a module, you can use the from import method to directly access the tool name
Import module name is to import all tools in the module at one time and pass the module name Access by tool name
Search path for module
When the python interpreter imports a module,
1. It will search the files with the specified module name in the current directory, and import them directly if any
2. If not, search the system directory
Principle - every file should be able to be imported
An independent py file is a module
When importing a file, all code in the file without any indentation is executed again
In the actual development scenario, each module is developed independently, and most of them are in the charge of special personnel
Developers usually add some test code under the module. These codes are only used to execute under the current module and do not need to be executed when imported into other files
__ name__ attribute
__ name__ Property enables the code of the test module to be run only in the case of test, and will not be executed in the case of import
name is a built-in property in python that records this string
If it is imported by other files, it records the module name
If it is the currently executed program, it records main
# Import module # Define global variables # Define class # Define function # At the bottom of the code def main(): pass # According to__ name__ Determine whether to execute the following code if __name__ == "__main__": main()
Package
A package is a special directory that contains multiple modules
There is a special file init py
Benefits of package: import package name can import all modules in the package at one time
If you need to use multiple different modules during development, you can package multiple files
To use the modules in the package externally, you need to use init Py specifies the list of modules provided to the outside world
# Specify the list of modules provided to the outside world in the init file from . import send_message from . import receive_message
File reading and writing
Role of documents
Save the data for a long time and use it when needed
How files are stored
In a computer, files are stored on disk in binary form
Routine of operating files
1. Open file
2. Read and write files
3. Close file if you forget to close the file, it will cause a waste of system resources
Often you forget to close the file f.close()
Therefore, using the with syntax can automatically close the file to avoid forgetting to close the operation
with open('readme.txt') as f: f.write(text)
Functions that manipulate files
One function (open) and three methods (read/write/close)
open opens the file and returns the file operation object
read reads the contents of the file into memory
write writes the specified content to a file
Close close file
The open function is responsible for opening the file and returning the file object. The read/write/close three methods need to be called through the file object
field name pointer
The file pointer marks where to start reading data
When you first open a file, the file pointer usually points to the beginning of the file
When the read method is executed, the file pointer moves to the end of the content
Therefore, if you execute the read method once and read all the contents, you will not be able to read the contents if you call the read method again
How to open a file
The open function opens the file as read-only by default
The syntax is as follows
f = open("file name", "Access mode")
r opens the file as read-only, which is the default mode. If the file does not exist, an exception is thrown
w opens the file in write only mode. If the file exists, it will be overwritten. If it does not exist, it will be created
a open the file by appending. If the file exists, move the file pointer to the end of the file and start writing
readline reads data by line. If the file is large, one-time reading will cause great pressure on the memory, so use readline
readline reads data line by line
Copy file case
# 1. Open the file file_read = open("README") file_write = open("README[Copy]", "w") # 2. Read and write files text = file_read.read() file_write.write(text) # 3. Close the file file_read.close() file_write.close()
# Large file reading method # 1. Open the file file_read = open("README") file_write = open("README[Copy]", "w") # 2. Read and write files while True: # Read a line text = file_read.readline() # Determine whether the content is read if not text: break file_write.write(text) # 3. Close the file file_read.close() file_write.close()
ASCII has 256 characters of American standard information interchange code
python2.x the default ASCII encoding format does not support Chinese
python3.x uses utf-8 encoding format by default
Eval function: the eval function evaluates the string as a valid expression and returns the operation result
Define in class__ call__ Method, you can call the contents of the call method directly through the object name ()
example
# __ call__ Use of methods # Using the object name () directly after creating the object will execute the operations in the class__ call__ method class Cat(object): def __init__(self): pass def __call__(self, *args, **kwargs): print('__call__') obj = Cat() obj() # ------------------ __call__