Beginners learn python series -- [Day43] inheritance of three object-oriented features and derivation methods of classes

Summary of today's content

  • Object specific functions
  • Dynamic and static method
  • Inheritance of three characteristics of object-oriented
  • The essence of inheritance
  • Search order of data and methods
  • Classic and new
  • Derived method

Object specific functions

1. We can't really realize the unique methods for objects:
(1) If it is in the overall situation, it is not unique;
(2) Public if in class
There is a feature in python, which is equivalent to the unique method of the object, that is, the functions defined in the class are bound to the object by default.

2. Take a chestnut

class Person:
   h_type = 'human beings'

   def __init__(self, name):  # Let objects have unique data
       self.name = name
   # Functions defined in classes are called methods
   def eat(self):  # A method that is common to multiple objects is also a method that is unique to multiple objects. When called, the object will be passed in as the first parameter
       print('%s Cooking'%self.name)

   def others(self,a,b):
       print('others Ha ha ha')
p1 = Person('jason')
p1.eat()  # eat(p1)     # jason is cooking
p2 = Person('kevin')
p2.eat()  # eat(p2)     # kevin is cooking
# How to understand the word binding
p3 = Person('oscar')
Person.eat(p3)          # oscar is cooking

p1 = Person('jason')
p1.others(1, 2)       # others hahaha

Person.others(p1,1,2)    # others hahaha        

Dynamic and static method

There are three types of dynamic and static methods, mainly for functions written in class body code

1. Methods bound to objects;
(1) Directly write in the class body code;
(2) Object call will automatically pass the object as the first parameter;
(3) Class call passes several arguments as long as there are several formal parameters.

class Student:
   school = 'Tsinghua University'
   # Methods bound to objects
   def run(self):  # self is used to receive objects
       print('Old six, run quickly!!!', self)
stu1 = Student()

2. Methods bound to classes:
The call of class will automatically pass the class as the first parameter

class Student:
   school = 'Tsinghua University'
   # Methods bound to objects
   def run(self):  # self is used to receive objects
       print('Old six, run quickly!!!', self)

   @classmethod  # Methods bound to classes
   def eat(cls):  # cls is used to receive classes
       print('Six, you are really talented', cls)
stu1 = Student()
# Call methods bound to classes
Student.eat()  # Class call will automatically pass the class as the first parameter >eat (student)
''' Six, you are really talented <class '__main__.Student'>'''
stu1.eat()  # Object call will automatically pass the class that generates the object as the first parameter >eat (student)
'''Six, you are really talented <class '__main__.Student'>'''       

3. Static method (ordinary function)

class Student:
   school = 'Tsinghua University'
   @staticmethod  # Static method
   def sleep(a, b):  # No matter who calls it, it must follow the ordinary function parameter passing method
       print('Old six, go to bed')
stu1 = Student()
# Call static method
# Class call
Student.sleep(1,2)
# Object call
stu1.sleep(1, 2)       

Inheritance of three characteristics of object-oriented

1. Three characteristics of object-oriented:
Succession; Encapsulation; polymorphic

2. Meaning of inheritance
(1) In real life, inheritance is actually used to describe the relationship between human resources
eg: the son inherits the father's property (owns all the resources of the father)
(2) In the programming world, inheritance is actually used to describe the relationship between classes
eg: class A inherits class B (having all the data and functions in class B)

3. Purpose of succession
(1) In real life, inheritance is to want to occupy others' property
eg: personal father, godfather, godmother, rich woman
(2) In the programming world, inheritance is to save code
eg: you can inherit one class or multiple classes

4. Inherited operation

class Class name (parent class):
	pass

(1) When defining a class, put parentheses after the class name;
(2) Fill in the class name you need to inherit in brackets;
(3) Multiple parent classes can be filled in brackets, separated by commas
Take a chestnut

# Parent class
class Father:
   money = 1000000000


   def run(self):
     print('Luxury car Villa')

# Subclass
class Son(Father):
   pass
print(Son.money)   # 1000000000
Son.run(11)     # Luxury car Villa

5. Description of inherited classes
(1) We call the inherited class: parent class, base class or superclass;
(2) We call the class of inherited class: subclass or derived class;

6. Find the parent class from left to right in brackets
If you have something in yourself, don't ask for it from the parent class

class F1:
   name = 'from f1'

class F2:
   name = 'from f2'

class F3:
   name = 'from f3'

class MyClass(F1,F2,F3):
   pass
print(MyClass.name)
# from f1----> from f2----> from f3

The essence of inheritance

1. Abstraction and inheritance
Abstract: extract the common data or functions of multiple classes to form a base class
Inheritance: white whoring resources in each base class from top to bottom

2. Take chestnuts for example:

class Person:
   def __init__(self,name,age,gender):
       self.name = name
       self.age = age
       self.gender = gender
class Teacher(Person):
   def teach_course(self):
       print('Teacher in class')
class Student(Teacher):
   def choice_course(self):
       print('Students' course selection')
stu1 = Student('jason',18,'male')
print(stu1.__dict__)
# {'name': 'jason', 'age': 18, 'gender': 'male'}

3. Form a contrast
Object: a combination of data and function
Class: a combination of the same data and functions of multiple objects
Parent class: a combination of the same data and functions of multiple classes

Search order of names

Hit the key!!! It mainly involves object search names, so almost all of them are:
Object's own class parent

1. Search order of names without inheritance
First search from the object itself, and then search in the class that generates the object if there is no one
Object > > > class

class Student:
   school = 'Tsinghua University'
   def choice_course(self):
       print('Selecting courses')
stu1 = Student()
print(stu1.school)  # Object lookup school does not have its own namespace, so it is Tsinghua University that looks for classes
stu1.school = 'Peking University'  # A new school is created in its own namespace
"""If the object names and writes assignment symbols and data values, the operation must be in its own namespace"""
print(stu1.school)  # Peking University
print(Student.school)  # Tsinghua University

2. Search order of names in the case of single inheritance
First, find the object itself, then the class that generates the object, and then the parent classes
Object > > > class > > > parent class
eg1:

class A:
   name = 'from A'
   pass
class B(A):
   # name = 'from B'
   pass
class C(B):
   # name = 'from C'
   pass
class MyClass(C):
   # name = 'from MyClass'
   pass
obj = MyClass()
# obj.name ='I'm sleepy!!! '
print(obj.name)

'''from A'''

As long as the object is involved, look up the name almost back to the beginning and look it up in turn
eg2:

class A1:
   def func1(self):
       print('from A1 func1')
   def func2(self):
       print('from A1 func2')
       self.func1()  # obj.func1()
class MyClass(A1):
   def func1(self):
       print('from MyClass func1')
obj = MyClass()
obj.func2()
'''
from A1 func2
from MyClass func1
'''

3. Search order of names in the case of multiple inheritance
(1) Non diamond inheritance (it will not be summed up in a custom class)
Depth first (each branch goes to the bottom and then switches)

(2) Diamond inheritance (finally summed up to a custom class)
Breadth first (the first few branches will not go until the last branch of the last class)

Special note: you can use the class point mro() method to view the search order of the object names generated by this class

Classic and new

1. Concept description
(1) Classic class
Classes that do not inherit object or its subclasses (inherit nothing)
(2) New type
Classes that inherit object or its subclasses

2. Description in different interpreters
(1) In python3, all classes inherit object by default
That means there are only new classes in python3
(2) In python2, there are classic classes and new classes
Because classic classes have no core functions, they are directly cut off in python3

3. Recommended usage
In the future, when defining classes, if there is no parent class we want to inherit, the following writing is generally recommended:

class MyClass(object):
      pass

Its purpose is to be compatible with python2

Derived method

Subclasses define methods that are exactly the same as the parent class and extend this function > > >: derivation

1. Function of derivation - super() built-in attribute

class Person:
   def __init__(self,name,age,gender):
       self.name = name
       self.age = age
      self.gender = gender

class Teacher(Person):
   def __init__(self,name,age,gender,level):
       super().__init__(name,age,gender)   # super is specially used for subclasses to call methods of the parent class
       self.level = level     # I added some by myself
class Student(Person):
   pass

2. The derived instance makes some changes to the list to add data.

class MyClass(list):
   def append(self, value):  # [] cut Hu
       if value == 'jason':
           print('jason Cannot add')  # output
           return
       super().append(value)


obj = MyClass()  # Generate an object []
obj.append('jason')
obj.append(111)
obj.append(222)
obj.append(333)
print(obj)  # [111, 222, 333]
print(MyClass.mro())  # View the search order of object names generated by this class

"""
jason Cannot add
[111, 222, 333]
[<class '__main__.MyClass'>, <class 'list'>, <class 'object'>]
"""

Tags: Python Django programming language

Posted by ChrisA on Sat, 30 Jul 2022 22:12:39 +0530