About Pytorch super()
Ref: https://blog.csdn.net/shiheyingzhe/article/details/83051471
super() has 2 major pros:
- Avoids using the base class explicitly
- Working with Multiple Inheritance
reminder:
- During super instantiation, it firstly tries to find the base class of the same level, if no such case, executes its own base class.
- No repeat call
Example1:
1 | class A(): |
2 | def __init__(self): |
3 | print('Call class A') |
4 | super(A, self).__init__() |
5 | print('Leave class A') |
6 | class B(A): |
7 | def __init__(self): |
8 | print('Call class B') |
9 | super(B,self).__init__() |
10 | print('Leave class B') |
11 | class C(A): |
12 | def __init__(self): |
13 | print('Call class C') |
14 | super(C,self).__init__() |
15 | print('Leave class C') |
16 | class D(A): |
17 | def __init__(self): |
18 | print('Call class D') |
19 | super(D, self).__init__() |
20 | print('Leave class D') |
21 | class E(B,C,D): |
22 | def __init__(self): |
23 | print('Call class E') |
24 | super(E, self).__init__() |
25 | print('Leave class E') |
26 | sample=E() |
27 | print(E.__mro__) |
the output:
1 | Call class E |
2 | Call class B |
3 | Call class C |
4 | Call class D |
5 | Call class A |
6 | Leave class A |
7 | Leave class D |
8 | Leave class C |
9 | Leave class B |
10 | Leave class E |
11 | (<class '__main__.E'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, <class '__main__.A'>, <class 'object'>) |
Example2:
1 | class A(): |
2 | def __init__(self): |
3 | print('Call class A') |
4 | print('Leave class A') |
5 | class B(A): |
6 | def __init__(self): |
7 | print('Call class B') |
8 | print('Leave class B') |
9 | class C(A): |
10 | def __init__(self): |
11 | print('Call class C') |
12 | super(C,self).__init__() |
13 | print('Leave class C') |
14 | class D(A): |
15 | def __init__(self): |
16 | print('Call class D') |
17 | super(D, self).__init__() |
18 | print('Leave class D') |
19 | class E(B,C,D): |
20 | def __init__(self): |
21 | print('Call class E') |
22 | B.__init__(self) |
23 | C.__init__(self) |
24 | D.__init__(self) |
25 | print('Leave class E') |
26 | sample=E() |
27 | print(E.__mro__) |
the output:
1 | Call class E |
2 | Call class B |
3 | Leave class B |
4 | Call class C |
5 | Call class D |
6 | Call class A |
7 | Leave class A |
8 | Leave class D |
9 | Leave class C |
10 | Call class D |
11 | Call class A |
12 | Leave class A |
13 | Leave class D |
14 | Leave class E |
15 | (<class '__main__.E'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, <class '__main__.A'>, <class 'object'>) |