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

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)Eric Torreborre
 
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 traverseLuka Jacobowitz
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
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 wholeIlan Godik
 
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 ScalaDmytro Mitin
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative FunctorsDavid Galichet
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
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!kenbot
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasionsLuka Jacobowitz
 
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 PSUGDavid 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 pythonEU 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 PythonTendayi Mawushe
 
"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 SchlawackFwdays
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonChristoph Matthies
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
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 PythonPython Ireland
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
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 examplesRobert Lujo
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptxsrinivasa gowda
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
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 ObjectsP3 InfoTech Solutions Pvt. Ltd.
 

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

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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 Scriptwesley chun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
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 2024The Digital Insurer
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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 Takeoffsammart93
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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 Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

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