Python Basics (Object Oriented)

1. Object-oriented concept

The process of classifying classes with common properties is called object orientation.

2. Matters needing attention

When defining a class, the first letter of the class name must be capitalized

3. Object-oriented case

 1 class Person(object):
 2 def __init__(self,name,age): #name,age can be understood as an attribute of the class; init is initialization; the function defined in the class is called the constructor/constructor
 3 self.name=name #Instance attribute
 4         self.age=age
 5         print("start")
 6 def __del__(self): #Cleanup operation
 7         print("end")
 8 def show(self): #self is the class itself and cannot be omitted
 9         print("name:{0},age:{1}".format(self.name,self.age))
10 obj=Person(name="wuya",age=18) #To call the variables, method functions, etc. in the class, you first need to instantiate the class; obj is the object after the class Person() is instantiated, and the class is instantiated The process is also the process of class initialization. The instantiation process of the class is also the process of initialization for the constructor (equal to the method of calling __init__)
11 obj.show()
12 #Person(name="wuya",age=18).show() #Call the method with the class name

The result of running the above code is:

4. The execution order of methods in the class: initialization method -> specific method -> cleaning method

5. Object-oriented features

1) Package

a. Instance attributes

b. Data attributes (variables in a class)

2) Inheritance

3) Polymorphism

6. Method:

a. Ordinary method: belongs to the object, also belongs to the class, can only read and write;

b. Feature method: belongs to the object, only has the read attribute, and the method cannot have formal parameters;

c. Static method: It belongs to a class and can only be called by the class name. Generally, data attributes are processed by static methods.

7. Encapsulation entry example

 1 class Animal(object):
 2     def __init__(self,age):
 3         self.age=age
 4     def getAge(self):
 5         return self.age
 6 def setAge (self, age):
 7         if age>10 and age<100:
 8 self.age=age #Allow to modify age
 9         else:
10 print("age error")
11 objAnimal=Animal(age=25) #Instantiation of the class
12 print(objAnimal.getAge()) #Output the call result of the method of getting the age
13 objAnimal.setAge(age=11) #Call the method to modify the age
14 print(objAnimal.getAge()) #Output the call result of the method of getting the age

8. Advanced examples of packaging

1 class Animal(object):
 2 address="Earth" #Data attribute
 3     def __init__(self,age):
 4 self.age=age #Instance attributes
 5     #     @staticmethod
 6 def address(self): #Static method, data attributes are handled using static methods
 7 return "Earth"
 8 def show(self,name="❀"): #Ordinary method, readable and writable
 9         print("it come from {0},and it's age is {1},and it's name is {2}".format(self.address(),self.age,name))
10     def func(self,**kwargs):
11         print(kwargs)
12     @property
13 def info(self): #Feature method, read-only (only output)
14         print("hello world")
15     @property
16 def getAge(self): #Attribute method, read-only (only return)
17         return self.age
18 objAnimal=Animal(age=30) #Instantiation of the class
19 objAnimal.show() #Call ordinary methods
20 #objAnimal.show(name="monkey")
21 # Animal().show(name="monkey")
22 # Animal(age=10).address()
23 objAnimal.func(name="cch",age=18,city="Xi'an")
24 objAnimal.info #Characteristic method call
25 print(Animal.address(""))
26 print(objAnimal.age)

9. Inheritance

1) Concept

Parent class (base class): the class that is inherited

Subclass (derived class): inherits from another class

2) The difference between Java and Python inheritance

Java is single inheritance, Python is multiple inheritance

3) What does the subclass inherit from the parent class:

a. Variables (data attributes)

b. Instance attributes

c. method

3) Method overriding

When the method of the parent class cannot meet the needs of the child class, the child class will override the method of the parent class, and the object after the instantiation of the child class calls the method, and the method of the child class is given priority.

 1 class Father(object):
 2 address="Xi'an"
 3     def __init__(self,name,age):
 4         self.name=name
 5         self.age=age
 6     def info(self):
 7         print("this is a father's method")
 8 class Son(Father):
 9     def __init__(self,name,age,score):
10 Father.__init__(self,name,age) #The subclass inherits the instance attributes of the parent class
11         self.score=score
12     def show(self):
13         print("name is {0},and age is {1},and score is {1}".format(self.name,self.age,self.score))
14 def info(self): #Method override of parent class
15         print("this is a son's method")
16 son=Son(name="wuya",age=18,score=99)
17 son.show()
18 print(son.address) #The subclass inherits the variable (data attribute) of the parent class
19 son.info() #No print, there is print in info(), when the function and the return value, the output function is empty. If the subclass overrides the method of the superclass, the object after the subclass is instantiated calls the method, and the method of the subclass is given priority.

The result of running the above code is:

10. Inheritance order

1) From top to bottom (preconditions):

a. Single inheritance

b. The subclass overrides the method of the superclass

2) From left to right (precondition): subclasses inherit multiple classes (subclasses can inherit multiple parent classes, but the parent classes must be in a sibling relationship.)

3) So in Python, based on the parsing order rules of MRO, the base class will be searched from left to right. If the first matching attribute class is found, the search will be stopped. If not, the search will continue until find the match

as long as you ask. MRO is actually implemented through a C3 linearization algorithm. Its core idea is:

Subclasses will outperform superclass checks

Multiple parent classes are checked sequentially according to their order in the list

If there are two valid choices for the next class, only the first one can be chosen (linear search)

11. Example of inheritance order

1 class Father(object):
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 def funM(self):
 6         print("father")
 7
 8 class Mother(object):
 9 def funM(self):
10         print("mother")
11
12 class Son(Father,Mother): #Subclass Son inherits two parent classes
13     def __init__(self,name,age,score):
14 Father.__init__(self,name,age) #Subclass Son inherits the instance attributes of parent classes Father and Mother
15         self.score=score
16
17 son=Son(name="ccj",age=18,score=100)
18 son.funM()
19 print(Son.mro()) #Use the class name to call mro to see the execution order of the class

The result of executing the above code is:

12. Example of subclass inheriting multiple non-similar parent classes

1 class Person(object):
 2     pass
 3
 4 class Father(Person):
 5     def __init__(self):
 6         pass
 7 def funM(self):
 8         print("father")
 9 class Mother(object):
10 def funM(self):
11         print("mother")
12
13 class Son(Person,Father): #Multiple parent classes inherited by subclasses are not the same level, the code will report an error, z subclasses can inherit multiple parent classes, but the parent classes must be in the same level relationship.
14 def __init__(self,score): 15 Father.__init__(self) 16 self.score=score 17 son=Son(score=90) 18 son.funM() 19 print(Son.mro())

The result of running the above code is;

13. Example of inheritance method call error

1 class Person(object):
 2     pass
 3
 4 class Father(Person):
 5     def __init__(self):
 6         pass
 7
 8 class Mother(Person):
 9 def funM(self):
10         print("mother")
11
12 class Son(Father): #There is no funM method in the parent class inherited by the subclass, and the code will report an error
13     def __init__(self,score):
14         Father.__init__(self)
15         self.score=score
16
17 son=Son(score=99)
18 son.funM()

The result of running the above code is:

14. Inherited method call error example correction

1 class Person(object):
 2 def funM(self):
 3         print("person")
 4
 5 class Father(Person):
 6     def __init__(self):
 7         pass
 8
 9 class Mother(Person):
10 def funM(self):
11         print("mother")
12
13 class Son(Father): #The parent class of the subclass inheritance method is Father
14     def __init__(self,score):
15         Father.__init__(self)
16         self.score=score
17
18 son=Son(score=99)
19 son.funM() #The subclass calls the method, first searches from the subclass, then from the inherited parent class, if not found, then from the parent class of the parent class.
20 print(Son.mro())

The result of running the above method is:

15. Inheriting historical issues

python2 is depth first, python3 is breadth first

 1 class A:
 2     def show(self):
 3         print('A')
 4
 5 class B(A):
 6     pass
 7
 8 class C(A):
 9     def show(self):
10         print('C')
11
12 class D(B,C):
13     pass
14
15 if __name__ == '__main__':
16     obj=D()
17 obj.show() #The result of execution in python2 is A, and the result of operation in pyhton3 is C

16. Polymorphism

The advantages of Dota can be summarized as follows:

Added ongoing flexibility

Added ongoing extra extensions

1 class Animal(object):
 2     def talk(self):
 3 print("Animals will bark")
 4
 5 class Dog(object):
 6     def talk(self):
 7 print("Dogs bark too")
 8
 9 class Cat(object):
10     def talk(self):
11 print("Cats can also bark")
12
13 def func(animal):
14 animal.talk()
15 if __name__ == '__main__':
16     dog=Dog()
17     func(animal=dog)

The result of running the above code is:

Guess you like

Origin blog.csdn.net/m0_59485658/article/details/125436223