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

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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