Compared with functions, object-oriented is a larger encapsulation, encapsulating multiple methods in an object according to responsibilities
Type 1.1
Class is a general term for a group of things with the same characteristics or behavior. It is abstract and cannot be used directly
- Features are called attributes
- Behavior is called method
Class is responsible for creating objects
1.2 object
An object is an instantiation of a class. It has properties and methods defined in which class
The naming of the class meets the big hump naming method:
1. Capitalize the first letter of each word
2. There is no underline between words
Characteristic description of object = attribute
Behavior description of object = method
Attributes and methods not involved in the requirements do not need to be considered
1.3 object oriented basic syntax
- dir built-in function
By using the dir built-in function to pass in the identifier or data, you can view all the properties and methods in the object
for example
def demo() dir(demo) demo.__Method name__
Hint__ Method name__ The methods of format are built-in methods and properties provided by python
- Define simple classes
class Class name: def Method 1(self,parameter list): pass def Method 2(self,parameter list): pass
When defining a method in a class, the first parameter must be self. See that self is not considered temporarily
Object variable = class name ()
class Cat: def eat(self): print("Eat fish") def drink(self): print("drink water") tom = Cat() tom.eat() tom.drink()
Using print to output the object variable can output the object referenced by this variable, which class is created, and the address in memory
The address of the new object variable created through Cat () is different every time, indicating that different objects are generated
- self parameter in method
The method called by an object, self is the reference of that object
Use self to output the name of each cat inside the method
Within the class encapsulated method, self represents the object of the current calling method itself.
When calling a method, the programmer does not need to pass the self parameter
Inside the method:
You can access the properties of an object through self
You can call other object methods through self
class Cat: def eat(self): #For the method called by an object, self is the reference of the object. The reference is self, and the formal parameter stores the address of the object print("%s Eat fish" % self.name) # I personally understand that when tom calls the eat method, self is tom def drink(self): print("%s drink water" % self.name) # A method that calls a property within a method tom = Cat() #tom = instantiated object variable for reference tom.name = 'Tom' #In this way, you can add attributes to the object externally (less used) tom.eat() tom.drink() jerry = Cat() jerry.name = 'Jerry' jerry.eat()
- Initialization method
When you create an object using the class name (), the following actions are automatically performed:
1. Allocate space for objects in memory - create objects
2. Set the initial value for the attribute of the object - initialization method__ init__ This method is the built-in method of the object
The init method is specifically used to define which attributes a class has
The following is the validation code
class Cat(): def __init__(self): print("This is an initialization method") # When you create an object with the class name (), the initialization method is called automatically__ init__ tom = Cat() print(tom)
Define properties inside initialization methods
In development, if you want to set the properties of the object instead of the default properties while creating the object, you can do it in the following three steps__ init__ Method for modification:
1. Define the attribute value you want to set as__ init__ Formal parameters of method
2. Use self. Attribute = formal parameter inside the method to accept externally passed parameters
3. When creating an object, use the class name (attribute 1, attribute 2...) to call
class Cat(): def __init__(self,new_name): print("This is an initialization method") # self. Property name = initial value of the property # self.name = 'TOM' self.name = new_name def eat(self): print("%s Eat fish" % self.name) # When you create an object with the class name (), the initialization method is called automatically__ init__,self is a parameter that does not need to be passed in tom = Cat('TOM') print(tom.name) tom.eat() lazy_cat = Cat('JERRY') lazy_cat.eat()
- Built in methods and properties
del
Objects are automatically called before they are destroyed in memory
class Cat: def __init__(self,new_name): self.name = new_name print("%s coming" % self.name) def __del__(self): print("%s be gone" % self.name) tom = Cat('TOM') #tom is a global variable, and all code is recycled after execution print(tom.name) tom.__del__() print('1')
__ str__ Method. print is used to output the object variable. By default, the object created by the class when the object referenced by this variable is output, as well as the address in memory (in hexadecimal)
If you want to print custom content when using print to output object variables in development, you can use the built-in method str
Object oriented encapsulation instance
An external class is used to create an object, and then the object calls a method
The details of object methods are encapsulated inside the class
Xiao mingai running example: None
Private properties and private methods
In actual development, some attributes and methods of objects may only be used inside the object, not outside
When defining a property or method, add two underscores in front of it to define a private property or method
class Women: def __init__(self,name): self.name = name self.__age = 11 def __secret(self): print("%s What is your age %d" % (self.name,self.__age)) xiaomei = Women('xiaomei') #Private property, which cannot be accessed directly from the outside, but can be accessed inside the object #print(xiaomei.__age) #Private methods are also not directly accessible to the outside world #xiaomei.__secret() ## ```Pseudo private properties and private methods inherit **Three characteristics of object oriented** 1.Encapsulation: encapsulate attributes and methods into an abstract class according to their responsibilities 2.Inheritance realizes code reuse, and the same code does not need to be written repeatedly 3.Polymorphic different objects call the same method to produce different execution results and increase the flexibility of the code ```python # The concept of inheritance: a subclass has all the methods and properties of its parent class # Basic statement # Class name (parent class): # Subclasses should encapsulate subclass specific properties and methods according to their responsibilities # Technical Term # Inheritance is transitive, and the child class has the properties and methods of the parent class of the parent class
1.2 method rewriting
When the method encapsulated by the parent class cannot meet the needs of the child class, the method can be overridden
There are two situations for overriding parent class methods:
1. Method of overriding parent class
If the method implementation of the parent class is completely different from that of the child class in development, you can override and rewrite the method implementation of the parent class in the child class
If the method of the parent class is overridden in a subclass (with the same name as the parent class method), the overridden method in the subclass will be called when the method is called using the subclass object
2. Extend the parent class method
If in development, the method implementation of the subclass includes the method implementation of the parent class
The method implementation originally encapsulated by the parent class is part of the method of the child class
You can use the extension method
1. Override the method of the parent class in the subclass, as in the first case
2. Use super(). Superclass method to call superclass method at the required position in subclass method
3. In other locations of subclass code, write subclass specific code implementation according to the needs of subclasses
About super
● super is a special class in Python
super() is an object created using the super class
● the most common scenario is to call the method implementation encapsulated in the parent class when overriding the parent class method
1.3 private properties and methods of parent class
If the public method of the parent class contains the private properties and methods of the parent class, the child class can access the private properties and methods of the parent class by calling the public method of the parent class
class A: def __init__(self): self.num1 = 100 self.__num2 = 200 def __test(self): print("Private method %d %d " % (self.num1,self.__num2)) # Objects can access private properties and methods of their own classes def test(self): print("Common method of parent class %d" % self.__num2) self.__test() class B(A): def demo(self): print("%d" % self.num1) self.test() b = B() b.demo() b.test()
Multiple inheritance
Concept: a subclass can have multiple superclasses and have all the properties and methods of the superclass
grammar
Class subclass name (parent class name 1, parent class name 2...)
pass
Multiple inheritance should be avoided for properties and methods with the same name between parent classes
MRO – method search order
object is the base class provided by python for all objects. It provides some built-in properties and methods, which can be viewed using the dir function
When defining classes in the future, if there is no parent class, it is recommended to uniformly use object as the base class
polymorphic
Different subclass objects call the same parent method to produce different execution effects
- It can increase the flexibility of code
- On the premise of inheriting and overriding parent class methods
- It is a method calling skill and will not affect the internal design of the class
Class properties
1.1 there is only one method of multiple objects in memory. When calling a method, you need to pass the reference of the object into the method, that is, self, so that the object can call the method externally
Instance property, instance method
1.2 class is a special object - class object
When the program runs, the class will also be loaded into memory
There is only one class object in memory. A class can create multiple instance objects
In addition to encapsulating the properties and methods of instances, class objects can also have their own properties and methods
1. Class attribute
2. Class method
Syntax for accessing class properties and calling class methods - class
Class properties and methods are shared by all objects of the class and accessed directly through the class name
Class attribute is the attribute defined in the class object. It is usually used to record the characteristics related to this class. Class attribute will not be used to record the characteristics of specific objects
Code examples are as follows:
class Tool(object): # Class is also an object and has its own properties and methods # Use assignment statements to define class properties and record the number of all tool objects count = 0 # Class properties def __init__(self,name): self.name = name # Instance properties # Let class attribute value + 1 Tool.count += 1 toll1 = Tool('axe') print(Tool.count)
1.3 attribute acquisition mechanism
Class method
@classmethod # Modifier def Class method name(cls): pass
The cls in the method is the reference of which class is called
When calling a class method through the class name, like the instance method, you do not need to pass in the self parameter. Inside the method:
1. Class properties can be accessed through cls
2. Call methods of other classes through cls
class Tool(object): # Class is also an object and has its own properties and methods # Use assignment statements to define class properties and record the number of all tool objects count = 0 # Class properties @classmethod def show_tool_count(cls): print("Number of tool objects%d" % cls.count) #Inside a class method, you need to use cls references to access class properties or other class methods def __init__(self,name): self.name = name # Instance properties # Let class attribute value + 1 Tool.count += 1 tool1 = Tool("axe") tool2 = Tool('Hammer') Tool.show_tool_count()
Class method - static method
● during development, if a method needs to be encapsulated in a class, this method:
You do not need to access instance properties or call instance methods, nor do you need to access class properties or call class methods
● at this time, the method can be encapsulated into a static method
The syntax is as follows:
@staticmethod
def static method name ();
pass
class Dog(object): @staticmethod def run(): print('The dog is running') # Static methods can be called by class name and static method - they can be called without creating objects Dog.run()
class Game(object): # To define a class attribute, you only need to directly assign a statement under class top_socre = 0 def __init__(self,player_name): self.player_name = player_name @staticmethod # Static method def show_help(): print("Help message: let zombies enter the gate") @classmethod # Class method def show_top_score(cls): print("The highest score in history is:%d" % cls.top_socre) def start_game(self): print("%s Enter the game....." % self.player_name) # 1. View the help information of the game Game.show_help() # Static methods and class methods do not need to create objects. They are called directly through class name and method # 2. View the highest score in history Game.show_top_score() # 3. Create game objects game_player1 = Game("Xiao Ming") game_player1.start_game() # The instance method needs to create an object first, and then let the instance object call the method
Case summary
1. Instance method - the instance attribute needs to be accessed inside the method, and the instance method
The class name. Can be used inside the instance method to access class properties or class methods
2. Class method - only class attributes need to be accessed inside the method
3. Static method - inside the method, there is no need to access instance properties and class properties
Static methods and class methods do not need to create objects. They are called directly through class name and method
The instance method needs to create an object first, and then let the instance object call the method
Singleton design pattern
1. Single instance – purpose: the object created by the class has only one instance in the system
Each time the class name () is executed, the memory address of the returned object is the same, that is, the same object is created continuously
2.__new__ Method - the built-in method in the class provided by object
When you create an object using the class name (), the Python interpreter first 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 the reference (address) of the object
After the Python interpreter obtains the reference of the object, it passes the reference as the first parameter to the_ init_ method
3.__new__ Method override
The code rewritten by the new method is very fixed!
Rewrite__ new__ The method must return super()__ new__ (cls)
● otherwise, the Python interpreter will not call the initialization method of the object if it cannot get the object reference with allocated space
● note: new_ Is a static method, which needs to actively pass cls parameters when calling
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) # Pass the cls parameter to the new method of the parent class to get the reference # 3. Only when the reference of the object is returned will the class call the init method and pass the reference into self return instance # Call the parent class method using the super(). Method name # object.__new__(cls) calling the parent class method in the subclass - the parent class name. The parent class method () def __init__(self): print('Player initialization') player = MusicPlayer() print(player)
Steps for creating a single instance:
1. Define a class attribute with an initial value of None, which is used to record the reference of the singleton object
2. Rewrite__ new__ method
3. If the class attribute is None, call the parent class method to allocate space and record the result in the class attribute
4. Return the object reference recorded in the class attribute
Operations that allow initialization actions to be performed only once: