Python Korea FB Group Seminar 2013 Jan. http://onoffmix.com/event/11742
Speaker Deck: https://speakerdeck.com/kroisse/why-you-should-use-super-though-it-sucks
Google docs: https://docs.google.com/presentation/d/1NaDrIReaKD8qJhkTfyDEnt_FMReVR6aHbZ7RJVBhKf8/pub
7. Old-fashioned way
class B(A):
def parts(self, lamp):
base = A.parts(self, lamp)
return base + [lamp]
class C(B):
def parts(self, lamp):
base = B.parts(self, lamp)
return sorted(base)
8. Using super() with new-style classes
class B(A):
def parts(self, lamp):
base = super(B, self).parts(lamp)
return base + [lamp]
class C(B):
def parts(self, lamp):
base = super(C, self).parts(lamp)
return sorted(base)
9. Diamond Problem
class D(B, C)
class B(A) class C(A)
class A(object)
10. class A(object): class B(A):
def say(self): def say(self):
print 'A', print 'B',
A.say(self)
class C(A): class D(B, C):
def say(self): def say(self):
print 'C', print 'D',
A.say(self) B.say(self)
C.say(self)
>>> D().say()
D B A C A
11. MRO
● Method Resolution Order
● linearize class hierarchy
○ using C3 algorithm
● only for new-style classes
12. class D(B, C)
class B(A) class C(A)
class A
(object)
D.__mro__ == (D, B, C, A, object)
C.__mro__ == (C, A, object)
B.__mro__ == (B, A, object)
A.__mro__ == (A, object)
13. B I
A D
object C G H
E F
I.__mro__ == (I, H, D, B, F, G, C, A, E, object)
H.__mro__ == (H, D, B, F, G, C, A, E, object)
D.__mro__ == (D, B, C, A, object)
B.__mro__ == (B, A, object)
F.__mro__ == (F, C, A, E, object)
G.__mro__ == (G, C, A, object)
C.__mro__ == (C, A, object)
A.__mro__ == (A, object)
E.__mro__ == (E, object)
14. class A(object): class B(A):
def say(self): def say(self):
print 'A', print 'B',
super(B, self).say()
class C(A): class D(B, C):
def say(self): def say(self):
print 'C', print 'D',
super(C, self).say() super(D, self).say()
D.__mro__ == (D, B, C, A, object)
>>> D().say()
D B C A
32. class A(object): class C(A):
def say(self): def say(self):
print 'A', print 'C',
super(C, self).say()
class B(A): class D(B, C):
def say(self): def say(self):
print 'B', print 'D',
A.say(self) super(D, self).say()
D.__mro__ == (D, B, C, A, object)
>>> D().say()
D B A
33. Remember #3:
● Don't mix both style
● Caution: classic classes (before Python 2.1)
○ obsoleted in Python 3.x
○ remained in some standard libs of Python 2.x
● Whether using super() or not
is a method signature.
34. Plenty of pitfalls in super()
● verbose syntax — fragile on copy & paste :)
● can't use: super(C, self)[0]
● super(C) ≠ super(C, C)
35. ...but we should use super()
● It's a standard.
● Safer to multiple inheritance
● If you mix with classic style,
everything will be broken.