Python inheritance

Iron Man 2022-01-15 01:47:02

The goal is

Single inheritance ;

Multiple inheritance ;

Three characteristics of object-oriented :

1)、 encapsulation according to duty take attribute and Method encapsulation To an abstract class in ;

2)、 Inherit Achieve code reuse , The same code does not need to be written repeatedly ;

3)、 polymorphic Different objects call the same method , Produce different execution results , Increase the flexibility of the code ;

1、 Single inheritance

1.1 Concept of inheritance 、 Grammar and characteristics

Concept of inheritance : Subclass Have Parent class All of the Method and attribute ;

  Do not use inherited classes

class Animal:
def eat(self):
print(" eat ")
def drink(self):
print(" drink ")
def run(self):
print(" run ")
def sleep(self):
print(" sleep ")
class Dog:
def eat(self):
print(" eat ")
def drink(self):
print(" drink ")
def run(self):
print(" run ")
def sleep(self):
print(" sleep ")
def bark(self):
print(" bark ")
# Create an object - Dog object
wangcai = Dog()
wangcai.eat()
wangcai.drink()
wangcai.run()
wangcai.sleep()
wangcai.bark()

1)、 The grammar of inheritance

class Class name ( Parent class name ):
pass

Subclass Inherited from Parent class , Can directly enjoy Encapsulated methods in the parent class , No need to redevelop ;

Subclass Should be based on duty , encapsulation Subclass specific Properties and methods ;

Use inheritance classes :

class Animal:
def eat(self):
print(" eat ---")
def drink(self):
print(" drink ---")
def run(self):
print(" run ---")
def sleep(self):
print(" sleep ---")
class Dog(Animal):
# A child class has all the properties and methods of the parent class
# def eat(self):
# print(" eat ")
#
# def drink(self):
# print(" drink ")
#
# def run(self):
# print(" run ")
#
# def sleep(self):
# print(" sleep ")
def bark(self):
print(" bark ")
# Create an object - Dog object
wangcai = Dog()
wangcai.eat()
wangcai.drink()
wangcai.run()
wangcai.sleep()
wangcai.bark()

2)、 Professional term

Dog class Animal Subclasses of classes ,Animal Class is Dog The parent of a class ,Dog class from Animal Class inheritance ;

Dog class Animal A derived class of the ,Animal Class is Dog Class base class ,Dog Class from Animal Class derivation ;


thank
Similar articles

2022-01-15

2022-01-15

2022-01-15