learn-python
68 строк · 2.8 Кб
1"""Multiple Inheritance
2
3@see: https://docs.python.org/3/tutorial/classes.html#multiple-inheritance
4
5Some classes may derive from multiple classes. This means that the derived class would have
6its attributes, along with the attributes of all the classes that it was derived from.
7"""
8
9
10def test_multiple_inheritance():
11"""Multiple Inheritance"""
12
13# pylint: disable=too-few-public-methods
14class Clock:
15"""Clock class"""
16
17time = '11:23 PM'
18
19def get_time(self):
20"""Get current time
21
22Method is hardcoded just for multiple inheritance illustration.
23"""
24return self.time
25
26# pylint: disable=too-few-public-methods
27class Calendar:
28"""Calendar class"""
29
30date = '12/08/2018'
31
32def get_date(self):
33"""Get current date
34
35Method is hardcoded just for multiple inheritance illustration.
36"""
37return self.date
38
39# Python supports a form of multiple inheritance as well. A class definition with multiple
40# base classes looks like this.
41class CalendarClock(Clock, Calendar):
42"""Class that uses multiple inheritance.
43
44For most purposes, in the simplest cases, you can think of the search for attributes
45inherited from a parent class as depth-first, left-to-right, not searching twice in the same
46class where there is an overlap in the hierarchy. Thus, if an attribute is not found in
47CalendarClock, it is searched for in Clock, then (recursively) in the base classes of
48Clock, and if it was not found there, it was searched for in Calendar, and so on.
49
50In fact, it is slightly more complex than that; the method resolution order changes
51dynamically to support cooperative calls to super(). This approach is known in some other
52multiple-inheritance languages as call-next-method and is more powerful than the super call
53found in single-inheritance languages.
54
55Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more
56diamond relationships (where at least one of the parent classes can be accessed through
57multiple paths from the bottommost class). For example, all classes inherit from object,
58so any case of multiple inheritance provides more than one path to reach object. To keep
59the base classes from being accessed more than once, the dynamic algorithm linearizes the
60search order in a way that preserves the left-to-right ordering specified in each class,
61that calls each parent only once, and that is monotonic (meaning that a class can be
62subclassed without affecting the precedence order of its parents).
63"""
64
65calendar_clock = CalendarClock()
66
67assert calendar_clock.get_date() == '12/08/2018'
68assert calendar_clock.get_time() == '11:23 PM'
69