Python object oriented

Posted by mniessen on Sat, 18 Sep 2021 07:27:13 +0200

Object oriented lesson 1: classes and objects

At the beginning, object-oriented allows developers to define their own data types. There are two cores: one is type (class for short) and the other is object (instance). As we learned earlier,

typeType nameobject
integerint-1,1,2,100
Floating point numberfloat3.14,10.1,-2.5
None typeNoneTypeNone
BooleanboolTrue,bool
character stringstr"hello world","good",...
listlist[1,2,3],['age','height','gender']
tupletuple{1,2,3}
aggregateset{1,2,3}
Dictionariesdict{'x':10,'y':100}

After reading so much, what are classes and objects? Let's make an analogy:

For example, classes are like the design drawings of cars, and objects are like vehicles running on the street to undertake transportation tasks., We use the types provided by Python as the cornerstone to create our own types, and python provides us with such syntax attacks

When writing a class, we should first write the name of the class. The class name should follow the big hump naming method. The so-called big hump naming method is to mix the names of upper and lower case classes. When the class name is a unique name composed of one or more words, the first letter of each word should be capitalized, which can increase the readability of the program.

  Writing a class requires three steps:

1: Declare a class, that is, translate the first row of the table into python

2: Declare attributes: translate the attributes in the table into code. Note that the attributes must have default values

You can create an object by adding parentheses to the class name. Creating an object is also called instantiating an object

For example: create a rectangular object:

print(Rectangle())#The address of the object in the heap is printed

Assign the created variable to a variable:

rect = Rectangle()

Then use the variable name. Property to access the value of the property

print(rect.length,rect.width)

Modify the value of the object attribute and use the variable name. Attribute = value.

rect= Rectangle()
rect.length = 5
rect.width = 2
print(rect.length,rect.width)

Collate into one function:

rect= Rectangle()
rect.length = 5
rect.width = 2
rect1= Rectangle()
rect1.length = 4
rect1.width = 3
def area(rect):        #Parameter accepts a rectangular object 
    returnrect.length *rect.width
print(area(rect) )     #Calculating rectangular objects
print(area(rect2))

3: Functions that represent behavior characteristics are written in classes and are often called methods

Calling a method in a class

class Rectangle: 
    length = 0 
    width = 0  
    def area(rect): 
        return rect.length *rect.width  
    def perimeter(rect): return 2 * (rect.length +rect.width)
rect = Rectangle()
rect.length = 3
rect.width = 4
print(rect.area())
print(rect.perimeter())

Magic method

The names of magic methods are fixed. Generally, we don't need to call them in an obvious way, but they will be executed automatically at a special stage.

__init__()

__str__()

__ init__ () function, you can modify the value of the attribute when instantiating the object

class Rectangle: 
    length = 0 
    width = 0  
    def __init__(self,length,width): 
        self.length =length 
        self.width =width  
    def area(rect): 
        returnrect.length *rect.width  
    def perimeter(rect): 
        return 2 * (rect.length +rect.width)

The magic function should be written in the class, so the init function has at least one parameter self. The parameter is passed to the modified attribute through the parameter. Generally, the parameter name is consistent with the attribute name. Once it is written__ init__ Function, and__ init__ If the function has other parameters besides self, it needs to be__ init__ The function passes in values for parameters other than self. You can also give__ init__ Sets the default value for the parameters of the function.

__ str__ Function, which requires to return a string. The information of this string should be able to organize the information of the object. When we use the print function to print the object, it is actually printed__ str__ The string returned by the function.

class Rectangle: 
    length = 0 
    width = 0  
    def __init__(self,length=0,width=0):
        self.length =length 
        self.width =width   
    def area(rect): 
        returnrect.length *rect.width  
    def perimeter(rect): 
        return 2 * (rect.length +rect.width  
    def __str__(self): 
        return 'What is the length of a rectangle' + str(self.length) + ',Wide is' + str(self.width) 
rect = Rectangle(3, 4)
print(rect)

encapsulation

         Public members can be used publicly, that is, they can be accessed inside a class or used in an external program. In Python, class member functions and member variables are public by default.

        Private members cannot be accessed directly outside the class. They are generally accessed and operated inside the class, or accessed outside the class by calling the public member method of the object, which is an important embodiment of the encapsulation characteristics of the class.

__ XXX: it starts with two underscores and indicates the private member of the class. Generally, only the class object can access it, and the subclass object cannot directly access the member, but it can be accessed through a special way such as "object name. Class name _xxx".

class Point: 
    x = 10 
    __y = 20 
    z = 30 
    def get_x(self): 
        returnself.x 
    def get_y(self): 
        return self.__y 
    def __get_z(self): 
        returnself.z

inherit

Single inheritance

         One of the main benefits of object-oriented programming is code reuse. One of the ways to realize this reuse is through inheritance mechanism. Inheritance is used to specify that a class will obtain most or all of its functions from its parent class. It is a feature of object-oriented programming. This is a very powerful function, which is convenient for users to make several or more modifications to existing classes to create a new class. A new class is called a subclass or derived class, and the main class that inherits properties from it is called a base class or a parent class. A subclass or derived class inherits the functions of the parent class and adds new functions to it. It contributes to code reusability.

class Derived class(Base class):  
    Derived intra class statements

Only by inheriting the action of the base class, you can access the properties and methods of the base class, which improves the scalability of the code.

characteristic:

• if there are__ init__ () method, then the base class__ init__ () method will not be called automatically. It needs to be called specifically in the construction of its derived class.

• if not in the derived class__ init__ () method, and there are in the base class__ init__ () method, then the base class__ init__ The () method is called automatically

• there are three methods to call a parent class:

Method 1: parent class name. Method name in the parent class (self, [parameter 1, parameter 2, parameter 3,...])

Method 2: super(). Method name in parent class ([parameter 1, parameter 2, parameter 3,...])

Method 3: Super (name of current class, self). Method name in parent class ([parameter 1, parameter 2, parameter 3,......])

• Python always finds the corresponding type of method first. If it cannot find the corresponding method in the derived class, it starts to find it one by one in the base class.

Everything has advantages and disadvantages: one weakness of inheritance is that a special class may have other special places, and a class may be defined under it. In this way, the line of inheritance will become longer and longer. If inheritance is used, any small change also needs to redefine a class, which is easy to cause explosive growth of classes, Generate a lot of subtly different subclasses. Therefore, there is a principle of "more combination and less inheritance".

Multiple inheritance

Python subclasses can inherit one base class or multiple base classes, which is called multiple inheritance. The syntax of multiple inheritance of class is as follows.

class Derived class(Base class 1,Base class 2,...): 
        Derived intra class statements

In Python 3. X, its search method follows the MRO principle and can be found through classes__ mro__ Property outputs the corresponding method search order. Note:__ mro__ Property displays all inheritance context and inheritance order of the specified class. If the specified class does not have some methods and properties, but the class with lineage relationship has these properties and methods, when accessing these methods and properties that the class itself does not have, the__ mro__ The displayed order is searched backward layer by layer until it is found.

polymorphic

Polymorphism means that the same method of the base class has different realizations and behaviors in different derived class objects. Different derived class objects call the same base class method and produce different execution results, which can increase the flexibility of external calling of the code. Polymorphism is based on inheriting and rewriting the parent class method. Polymorphism is only a skill of calling methods and will not affect the internal design of the class.

Don't say much, figure above:

#Polymorphism is not used
class ArmyDog(object): 
    def bite_enemy(self): 
        print("Pursue the enemy.")
class DrugDog(object): 
    def track_drug(self): 
        print("Trace drugs.")
class Person(object): 
    def work_with_army(self,dog): 
        dog.bite_enemy() 
    def work_with_drug(self,dog): 
        dog.track_drug()
person = Person()
person.work_with_army(ArmyDog())
person.work_with_drug(DrugDog())
#Use polymorphism

class Dog: 
    def work(self): 
        pass
class ArmyDog(Dog): 
    def work(self): 
        print("Pursue the enemy.")
class DrugDog(Dog): 
    def work(self): 
        print("Trace drugs.")
class Person: # As long as you can receive parent objects, you can receive child objects 
    def work_with_dog(self,dog): # As long as the parent object can work, the child object can work. And different subclasses will produce different execution effects. 
        dog.work() 
person = Person()
person.work_with_dog(ArmyDog())
person.work_with_dog(DrugDog())

Topics: Python OOP