Python object oriented programming

Posted by tpl41803 on Mon, 24 Jan 2022 15:14:53 +0100

01. Basic theory

1, Concept of object

1. Everything is an object

2. The object is a specific object

The attributes of ownership, the behavior of ownership, and the scattered are encapsulated into a whole. For example: Wang Xiaoer (attribute: name, age, height... Behavior: walking, eating, herding sheep...)

3. The embodiment of objects in python

python is a particularly thorough object-oriented programming (OOP) language (other languages include basic data types and object types)

2, The difference between process oriented and object oriented

1. Process oriented and object-oriented programming ideas

They all belong to a way of thinking to solve problems.

Process oriented: when solving problems, focus on each process (step) of solving problems

Object oriented: when solving a problem, focus on the objects needed to solve the problem

For example: wash the dishes after dinner (process oriented: drain, put the dishes, pour the detergent, brush and dry; object oriented: your skills, your object's skills...)

2. Comparison between process oriented and object-oriented

1) Both object-oriented and process-oriented are ways (Ideas) to solve problems. Object-oriented is a kind of encapsulation of process-oriented.

2) The most important thing of process oriented programming is to decompose a task into specific steps.

3) The most important thing of object-oriented programming is to divide objects according to their functions, find objects and determine their properties and behavior.

3. Steps from the idea of process oriented programming to object-oriented programming

1) List the specific implementation steps of a task;

2) Try to separate the function code in these implementation steps;

3) Divide these function code blocks into a certain object;

4) Abstract the corresponding class according to the object and the corresponding behavior;

3, Introduction to class

1. What is a class

The abstraction of the characteristics of a specific object

2. Role of class

Produce concrete objects according to abstract classes

For example: (category: bad youth attributes: age, height, weight... Behavior: eating, drinking, whoring and gambling... Object: Zhang San, Li Si, Wang Wu... All meet the above attributes and behaviors)

3. Composition of classes

Name, attribute (static eigenvalue), method (dynamic action)

Note: 1) the above attributes and methods are abstract concepts

2) after the object is generated, the object has specific attribute values and method implementations

4. Classes commonly used in life

1) Class: money object: specific one, two, one hundred

2) Class: Automobile object: Audi, BMW, Mercedes Benz

5. Differences between objects and classes

Object - > Abstract - > class - > instantiation - > object

02. Practice of object-oriented programming in python

1, Define a class (classic class, new class)

class Money:		#Class name: (the first letter of the class name should be capitalized without parentheses)
    pass
class renminbi(money):		#The inside of parentheses indicates the inheritance relationship

2, Create an object based on the class

one =Money()		#one is an object (an object can be created by * class name + a bracket *)
print(one)

3, Underlying operation when creating objects

ProcessOn online drawing (flow chart can be drawn)

4, Attribute correlation

1. Differences between attributes and variables and judgment basis

1) Difference: variables are "variable values that can be changed", and there are different access permissions (global variables and local variables) according to different locations

Properties are "properties belonging to an object" and can only be accessed through one object

2) Judgment basis: whether there is a host

2. Object properties

1) Add operation: dynamically add - > objects directly through objects Attribute = value

Class initialization method (construction method) - > int method

2) Query operation

3) Modify operation

4) Delete operation

#Define a class
class Person:
    pass
#Create an object based on this class
p=Person()
#Add attributes to object p
p.age=18
p.height=180
#Find all properties of the current object (return a dictionary)
p.__dict__
#Delete a property
del p.age

5) Note: unique properties cannot be accessed between different objects.

3. Class attribute

1) Add operation: class name Attribute = value; Write variable name = value in class

2) Query attribute: you can query by class or object

(python object search mechanism: take priority to the object itself to find the attribute. If it is not found, find the corresponding class according to the class, and then search in this class)

3) Modify attribute: can only be modified by class name, not by object

4) Delete: can only be deleted by class name, not by object

5) Note: memory storage of class attributes; Class properties are shared by objects

#Add properties to the class
class Money:
    age=18
    count=1
    pass
class Text:
    sex=male
#Change the class to which the object belongs
one=Money()
one.__class__=Text
#Modification of class properties
Money.age=22
#Delete properties of class
del Money.age

5, Method correlation

1. Concept of method

1) Concept of method: describe the behavior of a target (for example, describe how a person eats and drinks...) It is very similar to the function

——>All encapsulate a series of actions

——>Can be called to perform a series of actions

——>The main difference is the way of calling

#function
def eat():
    print(1)
    print(2)
    print(3)
eat()
#method
class Person:
    def eat2(self):
        print(1)
        print(2)
p=Person()
p.eat2()

2. Division of methods

1) Class, object, instance, instance object, instantiation

2) Division basis of method

Instance method: by default, the first parameter needs to receive an instance;

Class method: by default, the first parameter needs to receive a class;

Static method: quietly watch the first two loading forces, and the first parameter receives nothing by default;

be careful:

- > the division is based on the data type that the first parameter must receive

- > no matter what type of method it is, it is stored in the class, not in the instance

- > different types have different calling methods

- > focus on the use level of methods: syntax, rules of different types of methods, call of different types of methods, and design different methods to solve problems according to different problems

3) Method storage problem

3. Example method

1) Standard form

2) Standard call: use the instance to call the instance method (without manual transfer, the interpreter will be automatically transferred by the called object itself)

Note: if the instance method does not receive any parameters, an error will be reported.

#Create a class + instance method
class Person:
    def eat(self,food):
        print("be at  table",food)
#Standard call
p=Person()
p.eat("potato")
#————>Output: eating, potatoes

4. Class method

1) Standard form

2) Standard call: it can be called either through a class or an instance

#Create a class + class method
class Person:
    @classmethod		#Class method decorator
    def leifangfa(cls,a):
        print("This is a class method",cls,a)
#Standard call (either through class or instance)
Person.leifangfa(123)
#————- > output: This is a class method, < class'__ main__. Person>123

5. Static method

1) Standard form

2) Standard call: it can be called either through a class or an instance

#Create a class + static method
class Person:
    @staticmethod
    def jingtai():
        print("This is a static method")
#Standard call (either through class or instance)

6. Permissions for accessing different types of attributes in different types of methods

class person:
    age=0
    def shilifangfa(self):
        print(self.age)
        print(self.num)
    @classmethod
    def leifangfa(cls):
        print(cls.age)
        print(cls.num)

p=Person()
p.num=10

p.shilifangfa()		#Both the age and num attributes can be output
p.leifangfa()		#The age attribute can be output, and the num attribute will report an error

6, Supplement

1. Class related supplements

1) Metaclass: a class that creates a class object

2) Class description: (used for standard programming)

  • Purpose: it is convenient for you to clarify your logical thinking, facilitate communication during multi person cooperative development, and facilitate the generation of project documents

  • Description method: write comments on the line below the definition class, attribute and method, and use double quotation marks (indicate the effect, parameter, parameter meaning, parameter type [dynamic language parameter uncertain], whether there is a default value and return value)

  • Generate project documents: (you don't need to give all the source code to others, use help() to generate the project first)

Method 1: use python built-in module pydoc (refer to the course, learn and use now)

Method 2: use third-party modules Sphinx, epydoc and Doxygen (refer to the course, learn and use now)

2. Attribute related supplements

1) Privatize attributes (set a range for attributes with large access range to make their access range smaller)

It can be used for data protection and data filtering

  • Note: there is no real privatization support in python (only encrypted by name reorganization rules), but you can use underscores to complete the pseudo privatization effect (access by other means); Class properties (Methods) and instance properties (Methods) follow the same rules

  • Public attribute (x): class internal access - > Yes

    Subclass internal access - > Yes

    Access to other locations in the module - > warning

    Instance access - > warning

    Cross module access to import - > Yes

    from module import * - > Yes

  • Protected attribute (_y): class internal access - > Yes

Subclass internal access - > Yes

Access to other locations in the module - > Yes

Instance access - > Yes

Cross module access import - > error

from module import * - > error

#file1
_a=6
#file2
from file1 import *
print(_a)			#Protected will report an error
###########################################################################################
#file1
_a=6
__all__=['_a']		#Built in properties__ all__ Can be used to transmit protected parameters
#file2
from file1 import *
print(_a)		#It can be accessed normally
  • Private attribute (u_z): class internal access - > Yes

Subclass internal access - > error

Access to other locations in the module - > error

Instance access - > error

Cross module access import - > error

from module import * - > error reported

Note: you can also use__ all__= [''] make other modules accessible

  • Supplement: x_ Distinguish it from the built-in keywords in the system

                 _  _ x__ Special attributes built in the system (for example: _dict__, __ count_)

2) Read only attribute (an attribute [generally refers to instance attribute] can only be read but not written)

Some attributes can only be modified internally according to different scenes, but not externally, and can only be read.

For example: network speed attribute and network status attribute of computer class.

  • Set the read-only attribute (scheme 1): hide all and expose some [the @ property modifier will be used here]

First, it is realized by "double underline before attribute", and then it is partially disclosed by the public method.

class Person(object):
    def __init__(self):
#hide all
        self.__age=18

#Partial disclosure
    @property        #The main function is to use this method in the way of attributes
    def age(self):
        return self.__age

p=Person()
print(p.age)


'''
Classic class and new class (new class is recommended)
Classic class: no inheritance( object)
New class: with inheritance( object)
        Can pass'__bases__'Query inheritance class
python2.x If you define a class, it does not show inheritance from object,Then this class is a classic class.
python3.x Whether inheritance is displayed or not, the default is a new class
'''
'''
@property Decorator explanation 
1.Main role:Associate some "attribute related methods (delete, modify, query)" to an attribute. Commonly used to define or manage__X
2.property Use in new classes: (code 1)
3.property Use in classic classes: (code 2)(Generally not used (listen as you use)
'''

#Code 1
class Person(object):
    def __init_(self):
        self.__age=18
    @property        ##########Decorator 1: (check)
    def age(self):
        return self.__age
    @age.setter        #########Decorator 2: (modified)
    def age(self,value)
        self.__age=value
    @age.deleter       #########Decorator 3: (deleted)
    def x(self):
        del self.__age                      
                             
p=Person()
print(p.age)
print(p.age=90)
  • Set read-only attribute (scheme 2)
class Person:
    def __setattr__(self,key,value): 
    #When we pass examples When attribute = value, this method will be called when adding an attribute to an instance or modifying an attribute value
    #Only within this method will this attribute and the corresponding data be stored in the__ dict__ In the dictionary.
        print(key,value)
        #Step 1: determine whether the key is the name of the read-only attribute we want to set.
        if key=='age' and key in self.__dict__.keys():
            print('This property is read-only and cannot be set')
        #Part 2: if it is not the name of the read-only attribute, it is really added to this instance.
        else:
            self.__dict__[key]=value

3) Built in special attributes (when a class is defined or an instance is created through this class, the system automatically assigns some attributes that can be used directly to complete some small test operations or some application scenarios)

  • Class properties:__ dict__: Properties of class

                      __ bases__: Class (python is multi inheritance, java is single inheritance)

                      __ doc__: Class

                      __ name__: Class name

                      __ module__: The module where the class definition is located

  • Instance properties:__ dict__: Properties of the instance

                         __ class__: Class corresponding to the instance

class Person:
    age=19                        #Class properties
    def __init__(self):
        self.name='sz'            #Use the initialization method to define an instance property
    def run(self):
        print("run")
print(Person.__dict__)
print(Person.__bases__)
print(Person.__doc__)
print(Person.__name__)
print(Person.__module__)


P=Person()
print(P.__dict__)
print(P.__class__)

 2. Method related supplement

1) Privatization method (same as privatization attribute: name reorganization mechanism)

The method is only used inside the class and is not exposed to the outside world.

2) Built in special methods

  • Life cycle approach (described separately in the next section)
  • Information formatting operation:__ str__ Method: user oriented

                                    __ repr__ Methods: for developers and python interpreter

class Person:
    def __init__(self,n,a):
        self.name=n
        self.age=a
    def __str__(self):
        return "This person's name is:%s,This person's age is:%s"%(self.name,self.age)

p1=Person("sz",18)
p2=Person("zs",19)

print(p1)        #At this time, the module name + class name + memory address is no longer printed, but__ str__ Method, return
print(p2)
print(repr(p1))        #When there__ str__ Method can be used to print module name + class name + memory address
print(repr(p2))
  • Call operation:__ call__ Method so that the instantiated object has the ability to be called
class Person:
    def __call__(self,*args,**kwargs):
'''
    Use__call__Method, so that the instantiated object has the ability to be called.
    *args  Is in the form of tuples
    **kwargs  In dictionary form
    These two parameters ensure that any form can be transmitted
'''
        print("xxx",args,kwarge)
    pass
p=Person
p(123,456,name='sz')    #If not in the class__ call__ Method, an error will be reported; If any__ call__ Method, the__ call__ Methods.
  • Index operation
  • Slicing operation
  • iterator
  • Descriptor

03. Object oriented programming - comprehensive case

#Task: make a calculator to realize some basic operations, addition, subtraction, multiplication and division, and print results
#Process oriented programming is extremely complex and unsafe for continuous operation

#Design and optimization ideas: Packaging - > Security - > whether multiple simultaneous operations can be satisfied - > whether fault tolerance (robustness)
class Cacular:
    def __int__(self,num):		#Used to initialize a class. num is the initialized attribute value
        if not isinstance(num,int):	  #isinstance() function in Python is a built-in function in Python, which is used to judge whether a function is a known type, similar to type().
            raise TypeError("There is a problem with this data type. It should be integer data.") 
    #When an error occurs in the program, python will automatically throw an exception. You can also display the exception through raise and give a prompt through TypeError(). Once the raise statement is executed, the statements after raise cannot be executed.
        self.__result=num		#“__” It is privacy processing. Instances can only be called and queried, and cannot be modified
    def jia(self,n):
         if not isinstance(num,int):
            raise TypeError("There is a problem with this data type. It should be integer data.")
        self.__result+=n
    def jian(self,n):
         if not isinstance(num,int):
            raise TypeError("There is a problem with this data type. It should be integer data.")
        self.__result-=n
    def cheng(self,n)
     if not isinstance(num,int):
            raise TypeError("There is a problem with this data type. It should be integer data.")
        self.__result*=n
    def show(self):
        print("The result of the calculation is:%d"%self.__result)
c1=Cacular(2)
c1.jia(6)
c1.jian(4)
c1.cheng(5)
c1.show()
--------------------------------------------------------------------—
#Further optimization idea: the above code is too redundant and needs to be simplified -- > decorator (without changing the original code basis) - > private method of decorator
class Cacular:
    def __check_num_zsq(func):		#Decorator of private method
        def inner(self,n):
            if not isinstance(num,int):
            	raise TypeError("There is a problem with this data type. It should be integer data.")
            return func(self,n)		######################################################don't quite understand!!!
        return inner
    @__check_num_zsq		#Decorator
    def __int__(self,num):
        self.__result=num
    @__check_num_zsq
    def jia(self,n):
        self.__result+=n
    @__check_num_zsq
    def jian(self,n):
        self.__result-=n
    @__check_num_zsq
    def cheng(self,n)
        self.__result*=n
    def show(self):
        print("The result of the calculation is:%d"%self.__result)
--------------------------------------------------------------------—
#Add a new task: realize the voice broadcasting function at each step (similar to turning on the sound calculator)
#It can be realized either by installing a third-party library or by calling the interface of Windows operating system
#Design and optimization ideas: where to insert code - > simplify code - > use decorators without damaging the original structure (nested decoration)
import win32com.client
class Cacular:
    def __check_num_zsq(func):		#Decorator of private method
        def inner(self,n):
            if not isinstance(num,int):
            	raise TypeError("There is a problem with this data type. It should be integer data.")
            return func(self,n)		######################################################don't quite understand!!!
        return inner
    def __say(self,word):
        spearker=win32com.client.Dispatch("SAPI.ApVoice")		#Create a broadcast object
        speaker.Speak(word)			#Through this broadcaster object, you can directly play the corresponding voice string
    def __creat_say_zsq(word=""):
        def __say_zsq(func):
            def inner(self,n):
                self.__say(word+str(n))
                return func(self,n)
            return inner
        return __say__zsq
    @__check_num_zsq		#Decorator
    @__creat_say_zsq()
    def __int__(self,num):
        self.__result=num
    @__check_num_zsq
    @__creat_say_zsq("plus")
    def jia(self,n):
        self.__result+=n
    @__check_num_zsq
    @__creat_say_zsq("subtract")
    def jian(self,n):
        self.__result-=n
    @__check_num_zsq
    @__creat_say_zsq("multiply")
    def cheng(self,n)
        self.__result*=n
    def show(self):
        self.__say("The result of the calculation is:%d"%self.__result)
        print("The result of the calculation is:%d"%self.__result)

c1=Caculator(10)
c1.jia(6)
c1.jian(4)
c1.cheng(5)
c1.show

Topics: Python