directory

Destructor __del__()

Garbage collection mechanism

Reference counting

Mark-clear

Generational recycling

Rewrite __repr__() and __str__() functions

Access limits the __XX variable

Code in Chinese for people to shoot bullets

inheritance

The role of inheritance

The Student class inherits the Person class

Implementation of multiple inheritance

polymorphism

The advantages of polymorphism

Three necessary conditions for the existence of polymorphism


Destructor __del__()

Automatically called when an object is released

The destructor manually releases the object, which is no longer accessible

class Preson(object) :
    def say(self) :
        print(self.__class__)
    def __del__(self) :
        print("Destructor")

a = Preson()
a.say()
# Release object
del a
a.say()
Copy the code

Objects defined in a function are freed at the end of the function, which can be used to reduce memory space

def fun() :
    a = Preson()

fun()
Copy the code

 

Garbage collection mechanism

Python’s GC module mainly uses reference counting to track and collect garbage. In addition to reference counting, you can also solve the problem of circular references that container objects may produce through mark-clean. The efficiency of garbage collection can be further improved by exchanging space for time through generational recycling.

Reference counting

How it works: When a reference to an object is created or copied, the object’s reference count is increased by one. When a reference to an object is destroyed, the object’s reference count is reduced by 1. When the object’s reference count is reduced to 0, it means that the object is no longer used and can be freed from memory.

Advantages: Reference counting has the great advantage of being real-time; any memory that has no reference to it is immediately reclaimed, whereas other garbage collection techniques must be under special conditions to reclaim invalid memory.

Disadvantages: but it also has weaknesses, brought by the reference counting mechanism in the operation of the additional operation and maintenance of reference counting Python’s memory allocation and release, reference assignment is in direct proportion to the number of times, it is certainly more than other those garbage collection technology brought about by the additional operation just for recovery of the amount of memory related to low efficiency. Another big problem with reference technology is circular references. Because objects refer to each other, the reference of each object is never zero, so the memory used by these objects is never freed.

Mark-clear

Mark-clear only focuses on objects that might produce circular references. Obviously, immutable objects such as PyIntObject and PyStringObject cannot produce circular references because they cannot hold references to other objects internally. Circular references in Python always occur between Container objects, which are objects that can hold other objects internally, such as lists, dict, classes, and so on. The overhead of this method depends only on the number of Container objects.

Principles: 1. Find the collection of root objects as the starting point of garbage detection actions, and objects are some global references and function stack references, these references to the object can not be deleted; 2. Starting from the root object collection, follow each reference in the root object collection, if an object can be reached, it means that the object is reachable and will not be deleted. This process is the garbage detection stage. 3. When the detection stage is over, all objects are divided into reachable and unreachable parts. All reachable objects are reserved, and the memory occupied by other unreachable objects will be recycled, which is the garbage collection stage. (The underlying link is a linked list that connects objects in these collections.)

Disadvantages: Inefficient marking and cleaning processes.

Generational recycling

How it works: All memory blocks in the system are divided into collections based on their lifetime. Each collection becomes a generation. Python defines three generations of objects by default, and the frequency of garbage collection decreases with the lifetime of the generation. That is, the longer an object is alive, the less likely it is to be garbage, and the frequency of its garbage collection should be reduced. So how to measure this lifetime: it is usually measured by the number of garbage collection actions, and the more times an object goes through garbage collection, the longer the object will live.

 

Rewrite __repr__() and __str__() functions

Rewrite: Write the function definition again

__str__() : the method used by STR to describe the object, which is automatically called when the print object is called

__repr__() : A machine method called in the Python interpreter by typing the object name and enter

Note: in the absence of STR and with repr, STR = repr

class Preson(object) :
    def __init__(self,name,age,sex,height) :
        self.name = name
        self.age = age
        self.sex = sex
        self.height =height
    def __str__(self) :
        return "%s-%d-%s-%d" % (self.name,self.age,self.sex,self.height)

a = Preson("kkk".18."Male".170)
print(a)
Copy the code

 

Access limits the __XX variable

To keep an internal attribute from being accessed directly from the outside, prefix the attribute with two underscores __

In Python, a property becomes private when preceded by two underscores.

Properties are not directly accessible externally

class Preson(object) :
    def __init__(self,name,age,sex,height) :
        self.name = name
        self.__age = age
        self.__sex = sex
        self.__height =height

a = Preson("kkk".18."Male".170)
print(a.__age)
Copy the code

__age cannot be accessed directly because the Python interpreter changed __money to _Preson__money, which can still be accessed with _Preson__money, but this is not recommended. Variable names are interpreted differently by different interpreters

class Preson(object) :
    def __init__(self,name,age,sex,height) :
        self.name = name
        self.__age = age #_Preson__age
        self.__sex = sex
        self.__height =height

a = Preson("kkk".18."Male".170)
print(a._Preson__age)
Copy the code

In Python, variables (attributes) like __XXX__ are called special variables, not private variables, and can be accessed directly

In Python, a variable like _XXX can be accessed directly, but by convention, when we see a variable like this, it means “although it can be accessed directly, treat it as a private variable, don’t access it directly.”

 

Code in Chinese for people to shoot bullets

Class: Person Attribute: Gun Behavior: Firing Class: Gun Attribute: Magazine Behavior: Shooting Class: Magazine Attribute: Number of Bullets Behavior: ""
classCartridge (object) :
    def __init__(Self, number of bullets) :Self. Number of bullets = Number of bulletsclassGun (object) :
    def __init__(The self, a cartridge) :Self. Magazine = magazinedefShot (self) :
        ifSelf. = = cartridge0:
            print("No bullets.")
        else: self. Magazine -=1
            print("Remaining bullets: % D rounds"% self. Magazine)classPeople (object) :
    def __init__(The self, a gun) :Self. = gun gundefTo shoot (self) :Shoot ()Add 5 rounds to the magazineBulletbox = bulletbox (5). Number of bullets# Gun, give the clip to the gunGnu = gun (bulletbox)# people, give the gun to the peoplePerson = person (gun) person. Shoot () person. Shoot () person. Fire the gun.Copy the code

 

inheritance

There are two classes A and B, and when class B inherits from class A, it is class B that has all the attributes and methods of class A

Inheritance is when a subclass inherits the characteristics and behavior of its parent class, making its object (instance) have the instance fields and methods of its parent class, or a subclass inherits methods from its parent class, making it have the same behavior as its parent class.

Rabbits and sheep are herbivores, and lions and leopards are carnivores.

Herbivores and carnivores are animals.

So inheritance needs to conform to the relationship: IS-A, the parent class is more general, the child class is more specific.

Although both herbivores and carnivores are animals, they differ in their attributes and behaviors, so the subclass will have the general characteristics of its parent and will have its own characteristics.

The role of inheritance

Simplified code and reduced redundancy. Inheritance simplifies people’s understanding and description of things and can clearly reflect the hierarchical relationship between related classes.

Improved code robustness

Improved code security

Inheritance is the most effective way to construct, build and extend new classes from some relatively general ones.

Is the premise of polymorphism, but the use of inheritance also improves the coupling degree of the class.

The Student class inherits the Person class

class Student(Preson)

class Preson(object) :
    def run(self) :
        print("run")
    def eat(self,food) :
        print("eat "+food)
    def __init__(self,name,age) :
        self.name = name
        self.age = age

class Student(Preson) :
    pass

a = Student("wangming".18)
print(a.name)
a.run()
a.eat("orange")
Copy the code

Subclasses cannot inherit private attributes from their parent class

class Preson(object) :
    def run(self) :
        print("run")
    def eat(self,food) :
        print("eat "+food)
    def __init__(self,name,age,height) :
        self.name = name
        self.age = age
        self.__height = height

class Student(Preson) :
    pass

a = Student("wangming".18.20)
print(a.name)
print(a.height)
Copy the code

 

Implementation of multiple inheritance

The Child class inherits the Father and Mother classes

Note: The parent class has the same method name. By default, the parent class's method is called first in parenthesesCopy the code
class Father(object) :
    def __init__(self,money) :
        self.money = money
    def play(self) :
        print("play")
    def fun(self) :
        print("fun1")

class Mother(object) :
    def __init__(self,face) :
        self.face = face
    def eat(self) :
        print("eat")
    def fun(self) :
        print("fun2")

class Child(Father,Mother) :
    def __init__(self,money,face) :
        Father.__init__(self,money)
        Mother.__init__(self,face)

def main() :
    a = Child(1000."good")
    print(a.money, a.face)
    a.play()
    a.eat()
    By default, the method in the first row of parentheses is called
    a.fun()

if __name__ == '__main__':
    main()
Copy the code

 

polymorphism

Inheritance is a prerequisite for polymorphism

Polymorphism: Multiple forms of a transaction, the ability to have multiple different manifestations or forms of the same behavior

The advantages of polymorphism

  • 1. Decouple the types
  • 2. Replaceability
  • 3. Scalability
  • 4. The interface
  • 5. Flexibility
  • 6. Simplify

Three necessary conditions for the existence of polymorphism

  • inheritance
  • rewrite
  • A superclass reference points to a subclass object

Animal this business has many forms, people feed all kinds of animals

class Animal(object) :
    def __init__(self,name) :
        self.name = name
    def eat(self) :
        print(self.name+"Eat")

class Mouse(Animal) :
    def __init__(self, name) :
        super(Mouse,self).__init__(name)

class Cat(Animal) :
    def __init__(self, name) :
        super(Cat, self).__init__(name)

class Person(object) :
    # One method, 100 kinds of animals can eat, provided that the Animal is inherited from Animal
    def feed(self,animal) :
        print("Bring the food.")
        animal.eat()

def main() :
    tom = Mouse("tom")
    jerry = Cat("jerry")
    a = Person()
    a.feed(tom)
    a.feed(jerry)

if __name__ == '__main__':
    main()
Copy the code

 

 

Learn together and make progress together. If there are any mistakes, please comment