Getting started with Python -- object oriented

Keywords: Python Machine Learning Deep Learning

Basic overview of object oriented

  • Object oriented programming (OOP): more extensible and readable. Object oriented programming encapsulates data and operation data into objects. The way of organizing code and data is closer to human thinking and improves programming efficiency.
  • python supports many programming paradigms such as object-oriented, process oriented and functional programming

Differences and relations between object-oriented and process oriented programming

Process oriented thinking

  1. Write the code according to the problem-solving logic, and write the code from top to bottom according to the business logic,
  2. Process oriented programming: "logical flow of program", suitable for writing small-scale programs.
  3. When thinking about problems, first analyze 'how to implement according to steps', then disassemble the problem solving into several steps, and correspond these steps into methods to finally complete this function step by step
  4. No energy to consider other things, only focus on how to complete, so it is not suitable for large projects

object oriented thinking

  1. It is a python programming idea that binds data and functions together and encapsulates them, which can develop programs faster and reduce the rewriting process of repeated code
  2. Object oriented programming: "the relationship between objects in software", has more energy to do other things, so it is suitable for writing large-scale programs
  3. Way of thinking: noun - class - determine attributes and methods according to needs - determine the relationship between them
  4. Pay attention to the design thinking (let others do it), such as who to wash the car

For example:

The first way to wash the car (process oriented) - focus on the process

  1. I went to a treasure to buy car washing tools.
  2. Buy cloth, water pump and detergent according to your small budget.
  3. Slashed with the waiter for an hour, which was 2 yuan cheaper.
  4. After waiting for a week, the shopping arrived and began to wash the car
  5. Halfway through the washing, the water pump broke and the bubbles haven't been cleaned yet

The second way (object-oriented) - focus on results

  1. Find a reliable car wash
  2. Pay for the car wash

Functional formula

      Encapsulate a function code into a function, so you don't need to write it repeatedly in the future, just call the function

Object oriented & object oriented process:

Object oriented: according to people's systematic thinking mode of understanding the objective world, it adopts the concept of object (entity) to establish a model and simulate the objective world to analyze, design and implement software. (everything is an object)

Object oriented programming (OOP): it is a design and programming method to solve software reuse. This method describes the similar operation logic and operation, application data and state in the form of class, and reuses them in the form of object instance in the software system, so as to improve the efficiency of software development.

Object oriented basic functions

Inheritance, polymorphism, encapsulation (python cannot hide like other high-level languages, and encapsulation here is encapsulation in the logical sense), etc.

Benefits of object-oriented programming

It has stronger expansibility, better readability and simplifies the programming process. Object oriented programming is to encapsulate data and methods related to operation corresponding data into class objects.

Classes and objects

Class and object are important concepts in object-oriented programming

Class is a template. The template can contain multiple functions, which implement some functions

Object is an instance created according to the template, through which the functions in the class can be executed

Class is equivalent to the drawing for manufacturing a car, and the car manufactured with this drawing is equivalent to an object

class

  • Class: also known as class object, the instance of a class is called instance object, and a class is a combination of a series / multiple objects with the same or similar characteristics / attributes, behaviors / functions
  • Class consists of three parts
    Class name: class name
    Class attribute: a set of data (car color, size, etc.)
    Class method: the method (behavior) that allows operations on the (car running, reversing, etc.)
  • Class does not occupy memory space when it is created. Memory space is allocated only when it is instantiated

object

  • Object: an object is a real thing. It is the instantiation and visualization of a class,
  • A class is an abstraction of an object, and an object is an instance of a class

Class abstraction

A collection of a series of objects with the same (or similar) properties and behavior can be extracted as a class

Example 1: Xiao Ming goes shopping in his BMW
         Xiao Ming - > can abstract human beings
         BMW - > can abstract car classes

Example 2: abstract class in tank war
         Tank
         -- Class name: Tank
         -- Attribute: blood volume type
         -- Method: fire bullets
         wall
         -- Class name: Wall
         -- Attribute: blood volume type
         -- Method: block
         bullet
         -- Class name: Bullet
         -- Attribute: lethality

Syntax (classes and objects)

-The class name conforms to the identifier rule: the first letter is capitalized, and the large hump rule is adopted
-Properties and methods can be defined in the class body

-Attributes are used to describe data, and methods (i.e. functions) are used to describe data related operations
– init() method: initializes the created object. Initialization refers to "assigning values to instance attributes"
– new() method: used to create objects, but it is generally unnecessary to define this method

example:

 

 

# Define classes and objects
# Class structure class name attribute method
# class name:
#     attribute
#     method

class Person:
    '''
    Characteristics of counterpart
    '''
    # name='Xiao Ming'  #Class properties
    age=20       #Class properties
    '''
    Corresponding person's behavior example method
    '''
    def __init__(self):
        self.name='Xiao Ming'   #Instance properties
        pass
    def eat(parms):
        print("A big meal")
        pass
    def run(self):   #Example method
        print('Run fast')
        pass
    pass
def printInfo():
    '''
    Common method
    :return:
    '''
    pass
# Create an object [instantiation of class]
# Rule format object name = class name ()
xm=Person()
xm.eat() #Call function
xm.run()
print("{}Your age is:{}".format(xm.name,xm.age))

# Create another instance object
xw=Person()
xw.eat()  #Example method

 

class GoodStudent:
    def __init__(self,name,score): #self must be in the first argument
        self.name=name
        self.score=score
    def say_score(self):
        print("{0}Your score is:{1}".format(self.name,self.score))
s1=GoodStudent("hzh",18). #Call constructor
s1.say_score()

09.13

Constructor__ init__ ()

  • The python object consists of three parts: id (identity identification code), type (object type), and value (the value of the object, including attribute and method)
  • After you create an object, you need to define a constructor__ init__ () method is used to perform "initialization of instance object", that is, after the object is created, initialize the relevant properties of the current object without return value.
  • main points:
    -Fixed name, must be__ init__ ()
    -The first parameter is fixed and must be self #self. It refers to the instance object just created
    -Constructors are often used to initialize instance properties of instance objects
    -The constructor is called through type (parameter list). After calling, the created object returns the corresponding variable
    – init() method: initializes the created object. Initialization refers to "assigning values to instance attributes"
    – new() method: used to create objects, but it is generally unnecessary to define this method

Instance properties

  • Instance attribute: attribute subordinate to instance object, i.e. instance variable
    -Instance properties are generally__ int__ () method is defined by the following code: self. Instance property name = initial value
    -In other instance methods of this class, access through self: self. Instance property name
    -After the instance object is created, access through the instance object:
    Obg01 = class name () # create object, call__ init__ () initialize properties
    Obg01. Instance attribute name = value # to assign an existing attribute or add a new attribute

Example method

  • Instance method: a method that is subordinate to an instance object.
#Definition format of instance method
def Method name(self[,parameter list ]): 
    Function body

#Call format of instance method
 object.Method name([Argument list])

Python

  • main points
    -When defining an instance method, the first parameter must be self, and the self value is the current instance object
    -When calling an instance method, you do not need or cannot pass parameters to self, which is automatically passed by the interpreter.
  • Differences between functions and methods
    -It is essentially the same, which is a statement block to complete a function
    -Methods are called through objects. Methods are subordinate to specific instance objects. Ordinary functions do not have this feature.
    -Intuitively, the method definition needs to pass self, and the function does not.
  • Method call essence of instance object: a=Student() a.say_score() —> Student.say_ Score() < interpreter translation >
  • Other operations:
    -dir(obj): all attributes and methods of the object can be obtained
    -obj.dict: attribute dictionary of object
    -pass: empty statement
    -Isinstance (object, type): judge whether the object is of the specified type

Class properties and class methods

  • Class attribute is a property that belongs to class object, also known as class variable. Class attribute belongs to class object, so it can be shared by instance object. How to define class attribute:
class Class name:
    Class variable=Initial value

Python

  • Class properties can be read through "class name. Class variable name". Memory analysis:
  • Class method: a method subordinate to a class object, which is defined by the decorator @ classmethod
    -@classmethod must be on the line above the method
    -The first cls must be written; cls refers to the class object itself
    -Calling class method format: class name. Class method name (parameter list). In the parameter list, you do not need / cannot pass values to cls
    -Accessing instance properties and instance methods in class methods can cause errors
    -The subclass inherits the parent class by passing in cls as a subclass object, not as a parent object
@classmethod
def Class method name(cls[,parameter list ]): 
    Function body

Python

  • Static methods: methods that have nothing to do with "class objects". Static methods are no different from ordinary functions of ordinary modules, except that static methods are placed in the class namespace and need to be called through classes. Static methods are defined through the decorator * * @ staticmethod * *.
    -staticmethod must be on the line above the method
    -Calling static method format: class name. Static method name (parameter list)
    -Accessing instance properties and instance methods in static methods can cause errors
@staticmethod
def Static method name([parameter list ]):
    Function body

Python

095 _del _ method (destructor) and garbage collection mechanism

  • __del_ method: the destruct method, which is used to implement the operations required when the object is destroyed.
  • python implements an automatic garbage collection mechanism. When the object is not referenced (the reference count is 0), the garbage collector calls the _del_ method. The system automatically provides the _del_ method and does not need a custom destructor method

096 _call methods and callable objects

  • The object that defines the _call method is called a callable object, that is, the object can be called like a function
class SalaryAccount:
    def __call__(self,salary):
        print("wages")
        yearsalary=salary*12
        return dict(yearsalary=yearsalary)
a=SalaryAccount()
ptiny(a(3000)) #Print the called _ call and output the dictionary

Python

097 method

  • Methods are not overloaded: defining a method can have multiple call modes, which is equivalent to implementing the overloaded methods in other languages (multiple methods with duplicate names). Therefore, if multiple methods with duplicate names are defined in the class body, only the last method is valid.
    ! methods with duplicate names are not practical. Methods in python are not overloaded
  • Method dynamics: python is a dynamic language, which can add new methods to dynamic classes or dynamically modify existing methods of classes
#Dynamics of test methods
class Person:
    def work(self):
        print("work hard!")
def play_game(s):
    print("{s} palys game".format(s))
def work2(s):
    print("studing hard!")
Person.play=play_game #Add new method
p=Person
p.work()
p.play()

Person.work=wprk2 #Modify existing methods
p.work

Python

098-099 private methods and private properties: implementation encapsulation

  • python has no strict access control restrictions, which is different from other object-oriented languages. Key points of private properties and private methods:
    – the attributes starting with two underscores are private and others are public;
    -Private properties (Methods) can be accessed inside the class
    -Private properties (Methods) cannot be accessed directly outside the class
    -Private properties (Methods) can be accessed outside the class through "class name private property (method) name"
    ! methods are also attributes in nature, but are executed through ().
#Test private properties and private methods
class Employee:
    __emotion="happy"
    def __init__(self,name,age):
        self.name=name
        self.__age=age #Private property
    def __work(self):  #Private method
        print("work hard!")
        #Class calls private properties
        print("{0}'s age is {2}".format(self.name,self.__age)) 
        #Calling private class variables inside a class
        print(Employee.__emotion)
e=Employee("hzh",18)
print(e.name)
print(e._Employee__age) #print(e.age) cannot output the result because age is a private attribute

e._Employee__work() #Call private method
print(Employee._Employee__emotion)

Python

100 @property decorator

  • @Property: you can change the calling mode of a method into "property call"
#Simple test @ property
class Employee:
    @property #Change the calling mode of a method to "property call"
    def salary(self):
        print("salary run....")
        return 1000
emp1=Employee()
#emp1.salary()
print(emp1.salary)

#@Usage of property decorator
class Employee:
    def __init__(self,name,salary):
        self.__name=name
        self.__salary=salary
"""
    def get_salary(self):
        return self.__salary
    def set_salary(self,salary):
        if 1000

    @property
    def salary(self):
    return self.__salary
    @salary.setter #Property settings for salary
    def salary(self,salary):
        if 1000<salary<50000:
            self.__salary=salary
        else:
            print("Error")
emp1=Employee('hzh',10000)
print(emp1.salary)      
emp1.salary=-2000
print(emp1.salary)

Python

101-1 introduction to three characteristics of object-oriented

  • python: is an object-oriented language. It also supports three characteristics of object-oriented programming: inheritance, encapsulation (hiding) and polymorphism
  • Encapsulation (hiding): hide the attributes and implementation details of the object. You only need to provide the necessary methods externally to realize encapsulation through private attributes and private methods. python does not have a strict syntax level "access controller", which can be realized consciously
  • Inheritance: make the subclass have the characteristics of parent class and improve the reusability of code. It is an incremental evolution that can add functions or improve existing algorithms when the design of parent class remains unchanged.
  • Polymorphism: the same method call will produce different behaviors due to different objects

102-108 succession

102 definition and use of inheritance

  • Inheritance: an important means to realize "code reuse", supporting multiple inheritance < a word can inherit multiple subclasses >, syntax format:
    -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 some default attributes common to all classes
    When you define a subclass, you must re construct the constructor called the parent class in the constructor, that is, the parent class name.init(self, parameter list).
#Definition of inheritance
class Subclass class name[Parent class 1[,Parent class 2,...]]
    Class body

Python

#Basic use of test inheritance
class Person:
    def __init__(self,name,age):
        self.name=name
        self.__age=age. #Private property
    def say_age(self):
        print("i don't know")
class Student(Person):
    def __init__(self,name,age,score):
        #The calling parent class initialization method must be displayed, or the interpreter will not call back
        Person,__init__(self,name,age)
        self.score=score
s=Student("hzh",20,90)
s.say_age()
print(s.name)
print(s._Person__age) #Subclasses inherit private attributes, but they cannot be used directly. If you want to find them, you can find them through print(dir(s))

Python

103 inheritance and rewriting of class members

  • Member inheritance: subclasses inherit all members except the constructor of the parent class
  • Method override: a subclass can redefine the methods in the parent class, so it will override the methods of the parent class, which is called override
class Person:
    def __init__(self,name,age):
        self.name=name
        self.__age=age. #Private property
    def say_age(self):
        print("my age:",self__age)
    def say_introduce(self):
        print("my name is {}".format(self.name))
class Student(Person):
    def __init__(self,name,age,score):
        #The calling parent class initialization method must be displayed, or the interpreter will not call back
        Person,__init__(self,name,age)
        self.score=score

    def say_introduce(self):
    '''override method ,It is equivalent to overriding the method of the parent class'''
        print("Sorry,my name is {}".format(self.name))
s=Student("hzh",20,90)
s.say_age()
s.say_introduce()

Python

104 view the inheritance structure of the class and the object root class

  • Through class method mro() or class attribute__ mro__ You can output the inheritance structure of this class
class A:pass
class B(A):pass
class C(B):pass
print(C.mro()) #C->B->A->object

Python

  • Object class is the parent class of all classes, so all classes have the properties and methods of object class
    -You can view object properties through the built-in function dir() method
    -All attributes of object, Person as a subclass of object, contain all attributes
    -In fact, the instance method is also a property, but the type of the property is "method"

105 rewrite__ str__ () method

  • Object has a__ str__ The () method is used to return the "description of the object". The print() method is often used to help view multiple information. str() can be overridden
#Testing__ str__ ()
class Person:
    def __init__(self,name):
        self.name=name
    def __str__(self):
    '''Returns the description of the object'''
        return("my name:{}".format(self.name))
p=Person("hzh")
print(p) #__ str__ () implement rewriting

Python

106 multiple inheritance

  • Multiple inheritance: that is, a subclass has multiple direct parent classes, and the overall level of the class will become complex. Avoid using it as much as possible

107 mro()

  • python supports multiple inheritance. If the parent class includes methods with the same name, the interpreter will search from left to right when the child class does not specify the parent class name.
  • MROmethod resolution order: method resolution order. The class hierarchy can be obtained through the mro() method. Method resolution is also found through the "class hierarchy"

108 super() gets the definition of the parent class

  • super() gets the definition of the parent class, not the object of the parent class. If you want to get the method of the parent class in the child class, you can get it through the super() method.
class A:
    def say(self):
        print("A:",self)
class B(A):
    def say(self)
        #a.say(self)
        super().say()
        print("b:",self)
B().say()

Python

109 polymorphism

  • Polymorphic polymorphism: it means that the same method call may produce different behaviors due to different objects.
    -Key points: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes; There are two necessary conditions for the existence of polymorphism (inheritance and method rewriting)
class Man:
    def eat(self):
        print("None")
class Chinese(Man):
    def eat(self):
        print("chinese")
class English(Man):
    def eat(self):
        print("english")
def maneat(m):
    if isinstance(m,Man):
        m.eat()
    else:
        print("No One")
maneat(Chinese())
maneat(English())

Python

110 overloading of special methods and operators

  • python's operation is actually realized by calling special methods of objects. Each operator corresponds to a corresponding method
    +: add
    -: sub
    <,<=,==: lt_le__eq_ >,>=,!=: gt_ge__nq_
    |,^,&: or_xor__and_
    <<,>>: lshift_rshift__
    *,/,%,//: mul_truediv__mod__floordiv_
    **: pow
  • Common special methods
    init: construction method < object creation P = persepn() >
    del: destruct method < object recycling >
    repr,str: print, convert call: function call
    gatattr: dot operation
    setattr: attribute assignment
    getitem: index calculation
    setitem: index assignment
    len: length
#Overloading of test operators
class Person:
    def __init__(self,name):
        self.name=name
    def __and__(self,other):
        if isinstance(other,Person):
            return "{0}-{1}".format(self.name,other.name)
        else:
            renturn "error"
    def __mul__(self,other):
        if isinstance(other,int):
            return self.name*other
        else:
            return "error"
p1=Person("hzh")
p2=Person("terence")
x=p1+p2
print(x) #If not defined__ add__ An error will be reported
print(x*7)

Python

111 special properties

  • obj.dict: attribute dictionary of object
  • obj.class: the class to which the object belongs
  • class.bases: base class tuple of a class (multiple inheritance)
  • class.base: the base class of the class
  • class.mro: hierarchy of classes
  • class.subclasses(): subclass list

112 shallow and deep copies of objects

  • Variable assignment: two variables are formed, but they actually point to the same object
  • Shallow copy: when copy.copy() copies, the sub object content contained in the object is not copied, so the source object and the copy object will reference the same sub object
  • Deep copy: copy.deepcopy recursively copies the sub objects contained in the object. The sub objects referenced by the source object and the copy object are different

113 combination

  • "is a" relationship: inheritance can be used to enable subclasses to have methods and properties of the parent class
  • "has a" relationship: composition can be used to realize that one class has methods and properties of another class
#Reuse of test inheritance implementation code
class A1:
    def say_a1(self):
        print("a1a1a1")
class B1(A1):
    pass
b=B1()
b.say_a1()

#Test composition realizes code reuse
class A2:
    def say_a2(self):
        print("a2a2a2")
class B2:
    def __init__(self,a):
        self.a=a
c=A2()
d=B2(C)
d.a.say_a2()

114-115 design patterns and methods

  • Design pattern: it is the unique content of object-oriented language and a fixed practice when facing a certain kind of problems. The popular design patterns are GOF23 design patterns< Beginners mainly include factory mode and singleton mode >
  • Factory mode: it separates the creator from the caller, and uses a special factory class to uniformly manage and control the selected implementation class and creation object
  • singleton pattern: the core function is to ensure that a class has only one instance and provide a global access point to access the instance. It reduces the overhead of system resources. When an object needs more resources, it can generate a singleton object and then permanently reside in memory, so as to reduce the overhead.

115 design method

 

Posted by superman on Fri, 19 Nov 2021 12:14:19 -0800