4.2 Class Inheritance
In programming, we know the benefits of classes. Through classes, we can continuously instantiate objects. These objects have the same attributes and methods, which greatly improves the reusability of program code.
In some cases, if you want to create a new class, this class has all the properties and methods of the old class, and some other properties and methods, then it is unwise to redefine its display, this time can be achieved through inheritance.
Inheritance refers to a code organization that allows members of the same class to share their methods and data structures. In programming, inheritance usually refers to using members of the same class to create new classes, rather than creating a new class. This is because inheritance can make code easier to write and maintain, and it can simplify how code is organized.
继承的优点:
- Enhance code scalability: By using inheritance, you can create many different types of classes that can be extended to different application scenarios.
- Improve code maintainability: By using inheritance, objects of the same type can be divided into multiple small classes, thereby improving code maintainability.
For example: Now create an animal class: Animal, this animal class has two methods, namely吃
drinking睡
, then it can be defined in the program as follows:
class Animal:
def eat(self):
print('我饿了')
def sleep(self):
print('我困了')
animal = Animal()
animal.eat()
animal.sleep()
i'm hungry
i'm sleepy
Generally, animals have these two methods. Animal
As a template of the animal class, this has the most basic methods of animals. At this time, if you want to create new classes, such as mammals and birds, you can create them by inheriting the animal class:
class Mammal(Animal):
def walk(self):
print('我会走')
class Bird(Animal):
def fly(self):
print('我会飞')
mammal = Mammal()
bird = Bird()
mammal.walk()
mammal.sleep()
bird.fly()
bird.eat()
I can walk
I'm sleepy
I can fly
I'm hungry
We see that both the mammalian class and the bird class inherit eat
the and sleep
method of the animal class, and they each create a new method, which is walk
and respectively fly
.
In the above example, Animal类
being Mammal类
and Bird类
inheriting Animal类
is called Mammal类
and Bird类
, or . And and yes . _ Note that subclasses cannot inherit the private properties and methods of the parent class:父类
基类
超类
Mammal类
Bird类
Animal类
子类
from icecream import ic
class Animal:
def __init__(self):
self.a = 'A'
self.__b = 'B'
def __eat(self):
ic('我饿了')
def sleep(self):
ic('我困了')
class Mammal(Animal):
...
mammal = Mammal()
ic(mammal.a)
mammal.sleep()
try:
ic(mammal.__b)
except AttributeError as err:
ic(err)
try:
mammal.__eat()
except AttributeError as err:
ic(err)
14:28:56|> mammal.a: ‘A’
14:28:57|> ‘我困了’
14:28:57|> err: AttributeError(“‘Mammal’ object has no attribute ‘__b’”)
14:28:57|> err: AttributeError(“‘Mammal’ object has no attribute ‘__eat’”)
4.2.1 The __init__ method
In the definition of a class, there are some __
special methods beginning and ending by default. These methods are generally used to handle some special things. Such methods are usually called magic methods or magic methods.
__init__
Method is a very important method among many magic methods. This method is called when the class is initialized into an object. It is generally used to define some class attributes and run some custom methods that need to be run when the class is initialized.
from icecream import ic
class Animal:
def __init__(self, leg=4):
self.leg = leg
a = Animal()
ic(a.leg)
b = Animal(3)
ic(b.leg)
14:49:39|> a.leg: 4
14:49:39|> b.leg: 3
In the above code, because most animals have 4 legs, the leg of the Animal class is directly set to 4, so that after initialization, the output of a.leg is the default 4. Then an object b is initialized with the Animal class, but the leg passed in this time is 3, then after the initialization is to call the __init__ method, the output b.leg is 3.
4.2.2 super method
Usually the subclass can directly call the method in the parent class. If both the subclass and the parent class have __init__ methods that need to define some initialization attributes, then it is obviously not possible to directly call the __init__ method in the subclass to pass in parameters.
from icecream import ic
class Animal:
def __init__(self, leg=4):
self.leg = leg
self.type = '双足动物' if self.leg == 2 else '非双足动物'
class Mammal(Animal):
def __init__(self, leg):
self.leg = leg
a = Animal()
ic(a.leg)
ic(a.type)
m = Mammal(leg=2)
ic(m.leg)
ic(m.type)
15:11:48|> a.leg: 4
15:11:48|> a.type: ‘非双足动物’
15:11:48|> m.leg: 2
Traceback (most recent call last):
File “E:\t3.py”, line 21, in
ic(m.type)
AttributeError: ‘Mammal’ object has no attribute ‘type’
We see that although the Mammal class inherits the Animal class, the self.type attribute of the Animal class cannot be called. This is because only the __init__ method in the Mammal class is run after initialization and the __init__ method in the Animal class is not run.
In order to achieve that the incoming parameters are introduced by both the subclass and the parent class initialization, you only need to modify the code a little bit, call the __init__ of the parent class in the subclass initialization method __init__ and pass in the corresponding parameters:
from icecream import ic
class Animal:
def __init__(self, leg=4):
self.leg = leg
self.type = '双足动物' if self.leg == 2 else '非双足动物'
class Mammal(Animal):
def __init__(self, leg):
super().__init__(leg)
a = Animal()
ic(a.leg)
ic(a.type)
m = Mammal(leg=2)
ic(m.leg)
ic(m.type)
15:16:38|> a.leg: 4
15:16:39|> a.type: 'non-biped'
15:16:39|> m.leg: 2
15:16:39|> m.type: 'biped'
4.2.3 issubclass(x, A_tuple), isinstance(x, A_tuple) methods
These 2 methods return x
whether it is derived from another class or the same class. A_tuple can be a class or a tuple containing multiple classes. If it is a tuple, then:
issubclass(x, (A, B, ...)) is equivalent to: isinstance(x, A) or isinstance(x, B)... isinstance(x, (
A, B, ...)) is equivalent to: isinstance(x, A) or isinstance(x, B)...The difference between these two methods is the first parameter. For the issubclass method, the first parameter must be a class, while isinstance must be
an x
object x
.
from icecream import ic
class Animal:
...
class Mammal(Animal):
...
class Bird:
...
class Person(Mammal):
...
a = Animal()
m = Mammal()
b = Bird()
p = Person()
ic(issubclass(m.__class__, a.__class__))
ic(issubclass(m.__class__, b.__class__))
ic(isinstance(p.__class__, a.__class__))
ic(isinstance(p, p.__class__))
15:36:24|> issubclass(m.class, a.class): True
15:36:24|> issubclass(m.class, b.class): False
15:36:24|> isinstance(p.class, a.class): False
15:36:24|> isinstance(p, p.class): True