Python basic learning day 8

Time:2022-5-3

Python private properties, single inheritance, and method rewriting

1. Private attributes and methods

  • In actual development, some properties or methods of an object may only be used inside the object rather than being accessed outside
  • Private properties are properties that an object does not want to expose
  • A private method is a method that an object does not want to expose
  • When defining an attribute or method, add two underscores before the attribute or method name to define a private attribute or method
Before setting private properties:
class Girl:
    def __init__(self, name):
        self.name = name
        self.age = 18
    def secret(self):
        Print ("{} age is {}". Format (self. Name, self. Age))
Anna = girl ("Xiaomei")
Anna.secret()
Print ("Xiaomei")
Print (Anna. Age) # can access properties externally
Private properties cannot be accessed directly from the outside:
class Girl:
    def __init__(self, name):
        self.name = name
        self.__ Age = 18 # set age to private property
    def secret(self):
        Print ("{} age is {}". Format (self. Name, self. _age))
Anna = girl ("Xiaomei")
Anna.secret()
print(Anna)
#Private property, cannot be accessed by the outside world!
print(Anna.__age) 
"""
Program running results:
AttributeError: 'Girl' object has no attribute '__age'
"""
Private methods cannot be called directly outside
class Girl:
    #Define attributes
    def __init__(self, name):
        self.__name1 = name
        self.__ Age = 18 # if you want the property not to be called externally, you can define the property as private

    def __ Secret (self): # if you want a method not to be called externally, you can define it as a private method
        Print (the age of F "{self. _name1}" is {self. _age} ")
Xiaomei = girl ("Xiaomei")
"" "an object cannot access private properties or call private methods outside of a class."
Print (Xiaomei. _age) # object access properties
xiaomei.__ Call method with secret() # object
"""
""""
Program running results:
AttributeError: 'Girl' object has no attribute '__secret'
"""

2. Pseudo private attributes and private methods

In Python, there is no real private
When naming attributes and methods, some special processing is actually done to the name, making it inaccessible to the outside world
Processing method: add before the name_ Class name — >_ Class name__ name

Tip: in daily development, do not use this method to access private properties or private methods of objects

Anna = girl ("Xiaomei")
Anna._Girl__secret()
print(Anna._Girl__age)
print(Anna)

3. Succession

Three characteristics of object oriented

  1. Encapsulation encapsulates attributes and methods into an abstract class according to their responsibilities
  2. Inheritance realizes the reuse of code, 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

3.1 concept of inheritance

A subclass has all the methods and properties of its parent class
Python basic learning day 8

class Animal:
    def __init__(self):
        self.color = "grey"
    def eat(self):  #
        print("eat")
    def drink(self):
        print("drink")
    def run(self):
        print("run")
    def sleep(self):
        print("sleep")
#Create a dog class, which inherits from the animal class
class Dog(Animal):
    def bark(self):
        Print ("Wangwang")
#Create objects from dog classes
wangcai = Dog()
The print (Wangcai. Color) # subclass object can access the properties encapsulated by the parent class
wangcai. The bark () # subclass can independently develop its own methods according to its own needs
#Subclass object, which can access the methods encapsulated by the parent class
wangcai.eat()
wangcai.drink()
wangcai.run()
wangcai.sleep()
class XTQuan(Dog):
    def fly(self):
        print(" i can fly....")
xtdog = XTQuan()
xtdog.fly()
xtdog.bark()
xtdog.eat()
xtdog.sleep()

3.2 syntax of inheritance

Class subclass name (parent class name):
pass
Subclasses inherit from the parent class and can directly enjoy the encapsulated methods in the parent class without redevelopment
Subclasses should encapsulate subclass specific attributes and methods according to their responsibilities

Technical Term
Dog class is a subclass of animal class. Animal class is the parent class of dog class. Dog class inherits from animal class
Dog class is a derived class of animal class. Animal class is the base class of dog class. Dog class derives from animal class

3.3 transmissibility of inheritance

Class C inherits from class B, and class B inherits from class A
Then class C has all the attributes and methods of class B and class A
Subclasses have all the properties and methods encapsulated in the parent class and the parent class of the parent class

class Animal:
    def __init__(self):
        self.color = "grey"
    def eat(self):  #
        Print ("stand up and eat")
    def drink(self):
        print("drink"
    def run(self):
        print("run")
    def sleep(self):
        print("sleep")
class Dog(Animal):
    Def eat (self): # although the parent class has an eat method, it is not suitable for subclasses to use this method. It is necessary to override the method of the parent class
        "" "override parent method,",
                1. Completely overwrite the parent method. Only the name of the parent method is reserved. The functions of the parent method are not reserved and all are rewritten
                2. Extend the method based on the parent method (retain the function of the parent method)
        """
        super(). eat()  # super(). Retain the function of the parent method and extend the parent method
        Print ("dogs like to eat in pots ~")
    def bark(self):
        Print ("Wangwang")
# python 2. X extended inheritance
    def run(self):
        # print("run")
        Animal.run(self)  # super().run()
        Print ("bouncing away...)
wangcai = Dog()
wangcai.eat()
wangcai.run()

Private properties and methods of the parent class

  • Subclass objects cannot directly access the private properties or private methods of the parent class within their own methods
  • Subclass objects can indirectly access private properties or methods through the public methods of the parent class
    • Private attributes and methods are the privacy of objects, which are not open to the public, and the outside world and subclasses cannot be accessed directly
    • Private properties and methods are usually used to do internal things
class A:
    def __init__(self):
        self.num1 = 100
        self.__ Num2 = 200 # private attribute
    def __ Test (self): # private method
        Print (F "I am a private method, but I am inside the class and can access num1 --- > {self. Num1} & num2 --- > {self. _num2}")
    Def pub (self): # public method of parent class
        #The public method of the parent class can access its own private properties and call its own private methods
        Print (F "the public method of the parent class, which can access its own private attribute -- > {self. _num2}")
        #The public method of the parent class can call its own private method
        self.__test()
class B(A):
    #Can the private properties of the parent class be accessed inside the child class
    def demo(self):
        Print (F "whether the subclass can access the public attribute {self. Num1} of the parent class")#
        #Print (F "can the subclass access the private attribute of the parent class? --- > {self. _a_num2}") # pseudo private attribute, not recommended
        """
        Print (F "can a subclass access the private property of the parent class? --- > {self. _num2}") 
        #The error message is as follows: attributeerror: 'B' object has no attribute '_ B__ num2'.  Did you mean: '_ A__ num2'?
        """
        #Can the private method of the parent class be called inside the child class
        # self._ A__ Test() # pseudo private method is not recommended
        #Want to call the private property of the parent class when the child class accesses the private method of the parent class?
        #Idea 1: create a common method in the parent class. In this method, it is feasible to access the private properties of the parent class! Calling the private method of the parent class is feasible!
        #Idea 2: can a subclass call the public method of the parent class? --- > Yes, because the subclass can inherit the methods of the parent class
obj_b = B()
obj_b.demo()
obj_b.pub()

3.4 multi inheritance

A subclass can have more than one parent and have all the properties and methods of the parent
For example, children will inherit the characteristics of their father and mother

#Parent class 1
class Base1:
    def demo1(self):
        Print ("I am the Demo1 method of base1")
#Parent class 2
class Base2:
    def demo2(self):
        Print ("I am the demo2 method of base2")

#The subclass inherits from the parent class
class Derived(Base1,Base2):
    def test(self):
        self.demo1()
        self.demo2()
Obj = derived() # created subclass object
obj.test()
obj.demo1()
obj.demo2()

If there are methods with the same name in different parent classes, which parent class method will be called when the subclass object calls the method?
Tip: when developing, you should try to avoid this situation that is easy to cause confusion!

  • If there are properties or methods with the same name between parent classes, you should try to avoid using multiple inheritance

Python basic learning day 8

#Parent class 1
#Class base1: # essentially, the parent class also inherits from the object class
Class base1 (object): # this writing method is the same as class base1: by default
    def demo1_1(self):
        Print ("I am the Demo1 method of base1")
#Parent class 2
class Base2:
    def demo2(self):
        Print ("I am the Demo1 method of base2")

#The subclass inherits from the parent class
class Derived(Base2, Base1):  #
    def test(self):
        self.demo1()
obj = Derived()
# obj.test()
obj.demo1()
print(Derived.__mro__)  #  View the order in which the derivde class calls methods or accesses properties
"""
(<class '__main__.Derived'>, <class '__main__.Base2'>, <class '__main__.Base1'>, <class 'object'>)
When an object of the derived class calls a method or accesses an attribute, it is a search path
If objects cannot be found according to the search order, they will finally be searched in the object class, 
If the object class is found and there is no such method or attribute, an error will be reported
The object class is the parent of all classes
"""
"""
In multi inheritance, the method of the parent class has the same name. When the subclass calls the method of the parent class, it will choose the method of the parent class inherited first
    Note: during development, try not to have the same name as the method to avoid confusion.
    Suggestion: base1 --- > Demo1 can be modified to Demo1_ one
           Base2 - > Demo1 can be modified to demo2_ one
"""

4. Polymorphism

  • Encapsulation: encapsulating attributes and methods into an abstract class according to responsibilities
  • Inheritance realizes the reuse of code, and the same code does not need to be written repeatedly
    • Design skills
    • Subclasses write specific code for their specific needs
  • Polymorphic different subclass objects call the same parent method to produce different execution results
    • Polymorphism can increase the flexibility of 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 classes
      Python basic learning day 8
      Python basic learning day 8
"""
1. Encapsulate the method game in the dog class
Ordinary dogs just play
2. Define xiaotiandog to inherit from dog and override the game method
Howling dogs need to play in the sky
3. Define the person class and encapsulate a method to play with the dog
Inside the method, directly let the dog object call the game method
"""
class Dog(object):
    def __init__(self, name):
        self.name = name

   def game(self):
        Print (F "{self. Name} finish Frisbee ~")
class XTDog(Dog):
    #Class name, inherited from dog, attribute 1 is not required
    #2 rewrite the game method
    def game(self):
        super(). Game() # extension parent method
        Print (F "{self. Name} playing in the sky ~")
Wangcai = object generated by dog ("Wangcai") # Dog class
XT = object generated by xtdog ("Feitian Wangcai") # xtdog class
class Person(object):
    def __init__(self, name):
        self.name = name
    def game_with_dog(self, dog):
        Print (F "{self. Name} and {dog. Name} happy play ~")
        dog.game()
Xiaoming = person ("Xiao Ming")
xiaoming.game_with_dog(wangcai)
xiaoming.game_with_dog(xt)

Case summary
In the person class, you only need to let the dog object call the game method, and you don’t care what the dog is
The game method is defined in the dog parent class
When executing a program, different dog objects (these objects can inherit from a unified parent class, or they can be objects of a parent class or a child class) arguments are passed in, which will produce different execution effects

class Animal:
    def __init__(self, name):
        self.name = name
    def eat(self):
        Print (F "{self. Name} in eating...")
class Cat(Animal):
    def __init__(self, name):
        # super(Cat, self).__init__(name)
        super().__init__(name)  # super(Cat, self).__init__(name)
    def eat(self):
        super(Cat, self).eat()
        Print (F "{self. Name} want to eat fish...")
class Mouse(Animal):
    def __init__(self, name):
        super(Mouse, self).__init__(name)
    def eat(self):
        super(Mouse, self).eat()
        Print (F "f {self. Name} eat rice...)
class Tiger(Animal):
    def __init__(self, name):
        super(Tiger, self).__init__(name)
    def eat(self):
        super(Tiger, self).eat()
        Print (F "{self. Name} eat meat...")
Tom = cat ("Tom")
Jerry = mouse ("Jerry")
Tiger = tiger ("Tigger")
class Person(object):
    def feedAnimal(self,ani):
        Print (F "breeder feeding {ani. Name}")
        ani.eat()
feeder = Person()
feeder. Feedanimal (ToM) # is also the method that the breeder calls his own feedanimal. When the subclass object is called
feeder.feedAnimal(jerry)
feeder.feedAnimal(tiger)

5. Class attribute

Structure of class 5.1

Terminology – Examples

  1. Using object-oriented development, the first step is to design classes
  2. Create an object using the class name (). There are two steps to create an object:
    • Allocate space for objects in memorynew
    • Call initialization methodinitInitialize for object
  3. After the object is created, there is a real object instance in memory
    Python basic learning day 8
    Therefore, usually:
  4. The created object is called an instance of a class
  5. The act of creating an object is called instantiation
  6. The properties of an object are called instance properties
  7. The method called by an object is called an instance method

During program execution

  • Objects have their own instance properties
  • To call an object method, you can use self
    • Access your own properties
    • Call your own method
      conclusion
      Each object has its own independent memory space and saves its own different attributes
      There is only one method of multiple objects in memory. When calling a method, you need to pass the reference of the object to the inside of the method

Class is a special object
Everything in Python is an object:
Class AAA: the defined class belongs to class object
Obj1 = AAA () belongs to the instance object
When the program is running, the class will also be loaded into memory
In Python, a class is a special object — a class object
When the program is running, there is only one class object in memory. Many object instances can be created with one class
In addition to encapsulating the properties and methods of instances, class objects can have their own properties and methods
1. Class attribute
2. Class method
Pass the class name You can access the properties of the class or call the methods of the class
Python basic learning day 8

5.2 class attribute and instance attribute

Concept and use
The attribute defined in the class is the attribute of the object
It is usually used to record the characteristics related to this class
Class properties are not used to record the characteristics of specific objects

"""
Define a tool class
Each tool has its own name  instance attribute
Requirements -- know how many tool objects have been created using this class  class attributes
"""
class Tools(object):
    Count = 0 # class attribute, which is used to describe how many instances of this class are created
    def __ init__ (self, name): # initialization method, which is used to assign attribute values to objects (instances)
        self. Name = name # instance attribute
        #Count the number of objects created through this class
        #Idea: every time an object is created, it will be called once__ init__ (self) method, every time it is called__ init__ , Just do a + 1 operation on count
        Tools.count += 1
Tool1 = tools ("flashlight") # create instance
Tool2 = tools ("wrench")
Tool3 = tools ("kitchen knife")
Print (tools. Count) # outputs the number of objects created by the class
Print (tool1. Count) # note: the count attribute belongs to the class tools, but can be accessed by the instance
print(id(tool1.count), id(Tools.count))  # 1759695208752 1759695208752
tool1. Count = 100 # this definition method only adds an attribute count and a tool1 to tool1 Memory space of count
                   #It does not change the value of the class attribute               
print(id(tool1.count), id(Tools.count))  # 1759695211856 1759695208752
print(Tools.count)  # --->3

5.3 acquisition mechanism of class

There is an upward lookup mechanism for property acquisition in Python
Python basic learning day 8
Therefore, there are two ways to access class properties:

  • Class name Class properties
  • Object Class properties (not recommended)
    be careful
    If using objects Class attribute = value assignment statement, which will only add one attribute to the object and will not affect the value of class attribute
    Python basic learning day 8

6. Class method and static method

Class 6.1 method

  • Class attributes are attributes defined for class objects
    • It can be defined under the class keyword by using the assignment statement
    • Class properties class properties are used to record the characteristics associated with this class
  • Class method is to record the methods related to this class
    • Within a class method, you can directly access class properties or call other class methods
  • 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
    • The CLS in the method is the reference of which class is called
    • This parameter is similar to the first parameter of the instance method and self
    • You can also use other names when prompted, but you are used to CLS
  • The class method is called by the class name. When calling the method, there is no need to pass the CLS parameter
    • Inside the method, you can access class properties through CLS
    • You can also call other class methods through CLS
#Class attributes are attributes used to describe class objects
#Class method describes the method of a class
"""
Within a class method, you can directly access class properties or call other class methods
Requirements:
Define a tool class
Each tool has its own name
Requirement - encapsulate a show in the class_ tool_ The count class method outputs the number of objects created using the current class
"""
class Tools(object):
    count = 0
    def __init__(self, name):
        self.name = name
        Tools.count += 1
    #Create class method
    @classmethod
    def show_tool_count(cls):
        Print (F "currently {CLS. Count} tool instances have been created!")# Inside the class method, you can call other class methods if you access the class properties
        #Inside the print (self. Name) # class method, you cannot access instance properties or call instance methods
tool1 = Tools("burpsuit")
Tool2 = tools ("ice scorpion")
Tools.show_tool_count()

Static method

  • During development, if you need to encapsulate a method in a class, this method:
    • There is no 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 static method needs to be identified by the modifier @ staticmethod to tell the interpreter that this is a static method
  • Call the static method through the class name
class Dog:
    def __init__(self):
        self. Name = "Wangcai"
    @staticmethod
    def run():
        """
        A static method is defined. Static methods do not need to access instance properties or call instance methods
                            Static methods do not need to access class properties or call class methods
        """
        Print (F "the dog ran away...)
Wangcai = dog () # creates an instance from a class
wangcai.run()

6.3 case synthesis

"""
1. Design a game class
2. Properties
Define a class attribute top_ Score records the highest score in the history of the game
Define an instance property player_ Name records the player name of the current game
3. Method
Static method show_ Help displays game help information
Class method show_ top_ Score displays the highest score in history
Instance method start_ Game starts the current player's game
4. Main program steps
View help information
View the highest score in history
Create a game object and start the game
"""
import random
class Game(object):
    top_ Score = 0 # class attribute, which is used to record the highest score in history. The default is 0
    def __ init__ (self, name): # instance attribute, via__ init__ Instantiate
        self.player_name = name
    @Staticmethod # static method
    def show_help():
        Print ("welcome to the number guessing game...))
    @classmethod
    def show_ top_ Score (CLS): # class method that accesses class properties
        Print (F "the highest score in current history is {CLS. Top_score}")
    def start_ Game (self): # instance method
        Print (F "{self. Player_name} entered the game...")
        #Start the game and generate scores
        Game.top_score = random.randint(50, 1000)
        Print (F "{self. Player_name} gained {game. Top_score} points in the game")
Game.show_help()
Game.show_top_score()
Xiaoming = game ("Xiao Ming...")
xiaoming.start_game()
Game.show_top_score()
Xiaomei = game ("Xiaomei")

Case summary

  1. Instance method – the instance property needs to be accessed inside the method
    Class names can be used inside instance methods Access class properties
  2. Class method – only class properties or other class methods need to be accessed inside the method
  3. Static method – inside the method, there is no need to access instance properties and class properties

7. Single case design mode

7.1 design mode

-Design pattern is the summary and refinement of previous work. Generally, the widely circulated design is a mature scheme for a specific problem 
-The purpose of using design patterns is to reuse code, make code easier to be understood by others and ensure code reliability
  • Single case design mode
    • Purpose – let the object created by the class have only one instance in the system
    • The memory address of the object returned by the class name () is the same every time
  • Application scenario of single case design pattern
    • Music playing
    • recycle bin
    • object
    • printer
    • object
    • ……

7.2 newmethod

  • When creating an object using the class name (), the Python interpreter first callsnewMethod to allocate space for the object
  • newIt is a built-in static method provided by the object base class. It has two functions:
    • Allocate space for objects in memory
    • Returns a reference to an object
  • After the reference is obtained, it is passed to the Python interpreter as the first parameter__ init__ method

rewritenewMethod code is very fixed!

  • rewritenewMethod must return super()new(CLS), which is used to return the reference of the object
  • Otherwise, the Python interpreter will not call the initialization method of the object if it cannot get the object reference with allocated space
  • be careful:newIs a static method, which needs to actively pass CLS parameters when calling
    Python basic learning day 8

7.3 singleton in Python

Singleton – the object created by the class has only one instance in the system –  ensure the uniqueness of the reference
Define a class attribute with an initial value of none, which is used to record the reference of the singleton object
rewritenewmethod
If the class attribute is none, call the parent class method:newAllocate space and record the result in the class attribute, and return the object reference recorded in the class attribute
Python basic learning day 8
Perform initialization only once

  • Each time an object is created using the class name (), the Python interpreter automatically calls two methods:
    • newAllocate space
    • initObject initialization
  • RightnewAfter the method transformation, you will get the reference of the object created for the first time every time
  • However: the initialization method will be called again
'''
demand
Let the initialization action be executed only once
terms of settlement
Define a class attribute init_ Flag flag indicates whether initialization has been performed. The initialization value is false
In__ init__  Method, determine init_ Flag. If it is false, the initialization action will be executed
Then set init_ Flag set to true
In this way, it is called automatically again__ init__  Method, the initialization action will not be executed again
'''
class MusicPlayer(object):
    Instance = none # instance is set to the initial value none. If an object has been created,
    #That is, after calling the new method, the value of instance is not none
    init_ Flag = false # defines an initial value for marking__ init__ Method, not executed again
    def __ new__ (CLS, * args, * * kwargs): # override__ new__ method
        if cls. Instance is none: # if the new method has not been executed before, CLS instance is None
            cls. instance = super().__ new__ (CLS) # assign the memory ID to CLS instance
        return cls. Instance # overrides the new method and returns the memory ID
    def __init__(self):
        if MusicPlayer.init_flag == True:
            return
        Print ("player initialization")
        MusicPlayer.init_flag = True
player1 = MusicPlayer()
player2 = MusicPlayer()
Print (ID (player1)) # multiple instances 2918561262816 are referenced through__ new__ Returned
print(id(player2))

Recommended Today

Usage Summary of Python collaborative process (I)

1、 Python collaboration keyword Async: declare collaboration Note: the function declared through async is not a function, and a separate call will not be executed Await: it is used to wait for objects that can wait, including collaboration (that is, the collaboration declared by async), task (asyncio. Create_task(), asyncio ensure_ Future () is the task […]