SlideShare a Scribd company logo
1 of 36
Download to read offline
Why You Should Use
     super()
 Though It Sucks
       Eunchong YU
    kroisse@gmail.com
유은총

● Developing with Python for Food
● StyleShare     (2011-2012)
● SmartStudy (2012-)
● http://blog.materialistic.kr/
● https://github.com/kroisse
Extend
class A:
    def parts(self):
        return ['plate', 'nail']

class B(A):
    def parts(self):
        # old-way (before Python 2.2)
        base = A.parts(self)
        return base + ['screw']

>>> b = B()
>>> b.parts()
['plate', 'nail', 'screw']
class A(object): # new-style class
    def parts(self):
        return ['plate', 'nail']

class B(A):
    def parts(self):
        base = super(B, self).parts()
        return base + ['screw']

>>> b = B()
>>> b.parts()
['plate', 'nail', 'screw']
super(Class, self)
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)
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)
Diamond Problem

                  class D(B, C)




    class B(A)                     class C(A)




                 class A(object)
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
MRO
● Method Resolution Order
● linearize class hierarchy
   ○ using C3 algorithm
● only for new-style classes
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)
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)
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
super(Class, self)
to find current position   to traverse
            of the MRO     entire MRO
super(Class, self)
● only for new-style classes
● because classic classes don't have MRO
Why You Should Use
     super()
 Though It Sucks
Diamond, Again

                 class D(B, C)




    class B(A)                   class C(A)




                    class A
                   (object)
class A(object):              class C(A):
  def say(self):                def say(self, arg):
    print 'A',                    print 'C(%s)' % arg,
                                  super(C, self).say()

class B(A):                   class D(B, C):
  def say(self):                def say(self, arg):
    print 'B',                    print 'D(%s)' % arg,
    super(B, self).say()          super(D, self).say(arg)


   D.__mro__ == (D, B, C, A, object)
   >>> D().say(1)
   D(1)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "...", line ..., in say
   TypeError: say() takes exactly 1 argument (2 given)
super(Class, self)
● Does not call the superclass
● Call the next method in the MRO
● You can't expect what will be next
Remember #1:
● Don't change the method signature
  OR

● Send all received arguments to super()
class A(object):              class C(A):
  def say(self, arg):           def say(self, arg):
    print 'A',                    print 'C(%s)' % arg,
                                  super(C, self).say(arg)

class B(A):                   class D(B, C):
  def say(self, arg):           def say(self, arg):
    print 'B',                    print 'D(%s)' % arg,
    super(B, self).say(arg)       super(D, self).say(arg)




   >>> D().say(1)
   D(1) B C(1) A
class A(object):
  def say(self, *args, **kwargs):
    print 'A',

class B(A):
  def say(self, *args, **kwargs):
    print 'B',
    super(B, self).say(*args, **kwargs)

class C(A):
  def say(self, arg, *args, **kwargs):
    print 'C(%s)' % arg,
    super(C, self).say(arg, *args, **kwargs)

class D(B, C):
  def say(self, arg, *args, **kwargs):
    print 'D(%s)' % arg,
    super(D, self).say(arg, *args, **kwargs)
Initialize
class A(object):
    def __init__(self):
        print 'A: init'

class B(object):
    def __init__(self):
        print 'B: init'

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

>>> C()
A: init
<__main__.C object at 0x10157f150>
>>> # so where is B???
C.__mro__ == (C, A, B, object)

                   class C(A, B)




 class A(object)                   class B(object)




                      object
C.__mro__ == (C, A, B, object)

                   class C(A, B)




 class A(object)                   class B(object)




                      object
class A(object):
    def __init__(self):
        print 'A: init'
        super(A, self).__init__()

class B(object):
    def __init__(self):
        print 'B: init'
        super(B, self).__init__()

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

>>> C()
A: init
B: init
<__main__.C object at 0x10157f150>
class A(object):
    def __init__(self, *args, **kwargs):
        print 'A: init'
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print 'B: init'
        super(B, self).__init__(*args, **kwargs)

class C(A, B):
    def __init__(self, *args, **kwargs):
        super(C, self).__init__(*args, **kwargs)

>>> C('hello')
A: init
B: init
TypeError: object.__init__() takes no parameters
Remember #2:
● Don't forget super(C, self).__init__()

●   but how about arguments?
super(Me, self).__init__()
           vs.
  Parent.__init__(self)
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
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.
Plenty of pitfalls in super()
● verbose syntax — fragile on copy & paste :)
● can't use: super(C, self)[0]
● super(C) ≠ super(C, C)
...but we should use super()
● It's a standard.
● Safer to multiple inheritance
● If you mix with classic style,
  everything will be broken.
References:
●   https://fuhm.net/super-harmful/
●   https://groups.google.com/forum/?hl=en&fromgroups=#!topic/comp.lang.
    python/qswq2zIKS7I
●   http://www.python.org/download/releases/2.2.3/descrintro/#cooperation
●   http://docs.python.org/2/reference/datamodel.html#newstyle
●   http://www.python.org/dev/peps/pep-3135/
●   http://freshfoo.com/blog/object__init__takes_no_parameters

More Related Content

What's hot

Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUG
David Galichet
 

What's hot (19)

The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Scalaz
ScalazScalaz
Scalaz
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the whole
 
Introduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaIntroduction to programming with dependent types in Scala
Introduction to programming with dependent types in Scala
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Sigma type
Sigma typeSigma type
Sigma type
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Type classes
Type classesType classes
Type classes
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasions
 
Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUG
 

Similar to Why you should use super() though it sucks

Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 

Similar to Why you should use super() though it sucks (20)

Advanced python
Advanced pythonAdvanced python
Advanced python
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 
Revision1schema C programming
Revision1schema C programmingRevision1schema C programming
Revision1schema C programming
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
CSC Millionaire
CSC MillionaireCSC Millionaire
CSC Millionaire
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Type hints Python 3
Type hints  Python 3Type hints  Python 3
Type hints Python 3
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
 
Revision1 C programming
Revision1 C programmingRevision1 C programming
Revision1 C programming
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Oops Quiz
Oops QuizOops Quiz
Oops Quiz
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Why you should use super() though it sucks

  • 1. Why You Should Use super() Though It Sucks Eunchong YU kroisse@gmail.com
  • 2. 유은총 ● Developing with Python for Food ● StyleShare (2011-2012) ● SmartStudy (2012-) ● http://blog.materialistic.kr/ ● https://github.com/kroisse
  • 4. class A: def parts(self): return ['plate', 'nail'] class B(A): def parts(self): # old-way (before Python 2.2) base = A.parts(self) return base + ['screw'] >>> b = B() >>> b.parts() ['plate', 'nail', 'screw']
  • 5. class A(object): # new-style class def parts(self): return ['plate', 'nail'] class B(A): def parts(self): base = super(B, self).parts() return base + ['screw'] >>> b = B() >>> b.parts() ['plate', 'nail', 'screw']
  • 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
  • 15. super(Class, self) to find current position to traverse of the MRO entire MRO
  • 16. super(Class, self) ● only for new-style classes ● because classic classes don't have MRO
  • 17. Why You Should Use super() Though It Sucks
  • 18. Diamond, Again class D(B, C) class B(A) class C(A) class A (object)
  • 19. class A(object): class C(A): def say(self): def say(self, arg): print 'A', print 'C(%s)' % arg, super(C, self).say() class B(A): class D(B, C): def say(self): def say(self, arg): print 'B', print 'D(%s)' % arg, super(B, self).say() super(D, self).say(arg) D.__mro__ == (D, B, C, A, object) >>> D().say(1) D(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...", line ..., in say TypeError: say() takes exactly 1 argument (2 given)
  • 20. super(Class, self) ● Does not call the superclass ● Call the next method in the MRO ● You can't expect what will be next
  • 21. Remember #1: ● Don't change the method signature OR ● Send all received arguments to super()
  • 22. class A(object): class C(A): def say(self, arg): def say(self, arg): print 'A', print 'C(%s)' % arg, super(C, self).say(arg) class B(A): class D(B, C): def say(self, arg): def say(self, arg): print 'B', print 'D(%s)' % arg, super(B, self).say(arg) super(D, self).say(arg) >>> D().say(1) D(1) B C(1) A
  • 23. class A(object): def say(self, *args, **kwargs): print 'A', class B(A): def say(self, *args, **kwargs): print 'B', super(B, self).say(*args, **kwargs) class C(A): def say(self, arg, *args, **kwargs): print 'C(%s)' % arg, super(C, self).say(arg, *args, **kwargs) class D(B, C): def say(self, arg, *args, **kwargs): print 'D(%s)' % arg, super(D, self).say(arg, *args, **kwargs)
  • 25. class A(object): def __init__(self): print 'A: init' class B(object): def __init__(self): print 'B: init' class C(A, B): def __init__(self): super(C, self).__init__() >>> C() A: init <__main__.C object at 0x10157f150> >>> # so where is B???
  • 26. C.__mro__ == (C, A, B, object) class C(A, B) class A(object) class B(object) object
  • 27. C.__mro__ == (C, A, B, object) class C(A, B) class A(object) class B(object) object
  • 28. class A(object): def __init__(self): print 'A: init' super(A, self).__init__() class B(object): def __init__(self): print 'B: init' super(B, self).__init__() class C(A, B): def __init__(self): super(C, self).__init__() >>> C() A: init B: init <__main__.C object at 0x10157f150>
  • 29. class A(object): def __init__(self, *args, **kwargs): print 'A: init' super(A, self).__init__(*args, **kwargs) class B(object): def __init__(self, *args, **kwargs): print 'B: init' super(B, self).__init__(*args, **kwargs) class C(A, B): def __init__(self, *args, **kwargs): super(C, self).__init__(*args, **kwargs) >>> C('hello') A: init B: init TypeError: object.__init__() takes no parameters
  • 30. Remember #2: ● Don't forget super(C, self).__init__() ● but how about arguments?
  • 31. super(Me, self).__init__() vs. Parent.__init__(self)
  • 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.
  • 36. References: ● https://fuhm.net/super-harmful/ ● https://groups.google.com/forum/?hl=en&fromgroups=#!topic/comp.lang. python/qswq2zIKS7I ● http://www.python.org/download/releases/2.2.3/descrintro/#cooperation ● http://docs.python.org/2/reference/datamodel.html#newstyle ● http://www.python.org/dev/peps/pep-3135/ ● http://freshfoo.com/blog/object__init__takes_no_parameters