Detailed Explanation of Three Object Oriented Features of python

  • 2021-12-11 18:18:05
  • OfStack

Directory 1. Object-oriented 3 features introduction 1, encapsulation (hidden)
2. Inheritance
3. Polymorphism
2. Inheritance 1, Syntax Format 2, Class Member Inheritance and Rewriting 3, super () Obtaining Parent Class Definition 4, Design Pattern _ Factory Pattern Implementation 5, Design Pattern _ Singleton Pattern Implementation Summary

1. Introduction of three characteristics of object-oriented

Python is an object-oriented language, and it also supports three characteristics of object-oriented programming: inheritance, encapsulation (hiding) and polymorphism.

1. Encapsulate (hide)

Hide the properties and implementation details of objects, and only provide necessary methods to the outside world.

"Encapsulation" is realized by means of "private attributes and private methods". Python pursues concise grammar

2. Inheritance

Inheritance can make subclasses have the characteristics of parent classes, which improves the reusability of code. It is an incremental evolution in design. If the original parent class design remains unchanged, new functions can be added or existing algorithms can be improved.

3. Polymorphism

Polymorphism means that the same method call will produce different behaviors due to different objects. There are many examples in life: the same way of rest, different people have different ways of rest. Zhang 3 rest is sleeping, Li 4 rest is playing games, and programmers rest is "knocking a few lines of code".

2. Succession

Inheritance is an important feature of object-oriented programming, and it is also an important means to realize "code reuse".
If a new class inherits from a designed class, it will have the characteristics of an existing class directly, which greatly reduces the work
Difficulty. Existing classes are called "parent classes or base classes", and new classes are called "subclasses or derived classes".

1. Syntax format

Python supports multiple inheritance, and a subclass can inherit multiple parent classes. The inherited syntax format is as follows:

class Subclass Name (Parent 1 [, Parent 2,...]):

Class body: If no parent class is specified in the class definition, the default parent class is the object class. That is, object is the parent class of all classes, which defines a number of default implementations common to all classes, such as: __new__ ().

When you define a subclass, you must call the constructor of the parent class in its constructor. The invocation format is as follows:

Parent class name.__init__ (self, parameter list)


class Person:
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    def say_age(self):
        print(" Age is: ",self.__age)
class Student(Person):
    def __init__(self,name,age,grade):
        self.grade = grade
        Person.__init__(self,name,age) 
#  Constructor contains a call to the parent class constructor. According to the need, not necessary.   Subclass does not automatically call the parent class's __init__() , I 
#  They must call it explicitly. 
if __name__ == '__main__':
    s=Student(' Zhuge ',18,1)
    s.say_age()

2. Inheritance and overriding of class members

1. Member inheritance: The child class inherits all members of the parent class except the constructor.

2. Method overrides: Subclasses can redefine methods in the parent class, thus overriding the parent class's methods, also known as "overrides."


class Person:
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    def say_age(self):
        print(" Age is: ",self.__age)
class Student(Person):
    def __init__(self,name,age,grade):
        self.grade = grade
        Person.__init__(self,name,age) 
    def say_age(self):
        print(self.name," The age is: ",self.age)
#  Constructor contains a call to the parent class constructor. According to the need, not necessary.   Subclass does not automatically call the parent class's __init__() , I 
#  They must call it explicitly. 
if __name__ == '__main__':
    s=Student(' Zhuge ',18,1)
    s.say_age()

3. super () gets the parent class definition

In the child class, if you want to get the method of the parent class, we can do it through super ().

super () represents the definition of the parent class, not the parent class object.


class A:
    def say(self):
        print("A: ",self)
        print("say AAA")
class B(A):
    def say(self):
        #A.say(self)  Call the parent class's  say  Method 
        super().say() # Pass  super() Call the method of the parent class 
        print("say BBB")
if __name__ =="__main__:
    b = B()
    b.say()

4. Design Pattern _ Factory Pattern Implementation

Factory pattern realizes the separation of creator and caller. Using special factory classes will select implementation classes and create objects for unified management and control.


class CarFactory:
    def createCar(self,brand):
        if brand == "1":
            return one()
        elif brand == "2":
            return two()
        elif brand == '3':
            return three()
        else:
            return " Unknown brand, unable to create "
class one:
    pass
class two:
    pass
class three:
    pass
factory = CarFactory()
c1 = factory.createCar("1")
c2 = factory.createCar("2")
print(c1)
print(c2)

5. Design Pattern _ Singleton Pattern Implementation

The central role of the singleton pattern (Singleton Pattern) is to ensure that there is only one instance of a class and to provide a global access point to that instance.

Singleton pattern only generates one instance object, which reduces the overhead of system resources. When the generation of an object requires more resources, such as reading configuration files and generating other dependent objects, a "singleton object" can be generated and then permanently resided in memory, thus greatly reducing the overhead.


class One:
    __obj = None   #   Used to store this singleton 
    __init_flag = True
    def __new__(cls, *args, **kwargs):
         #  It refers to One Inside this class    Class attribute 
         if cls.__obj == None:
               # object  Is the default parent of a class 
             cls.__obj = object.__new__(cls)
         return cls.__obj
    def __init__(self,name):
        if One.__init_flag:
            print( "init....")
            self.name = name
            One.__init_flag = False
if __name__=='__main__':
    a = One( "aa")
    print(a)
    b = One( "bb")
    print(b)

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: