Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created May 30, 2016 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wilfred/ad309ecb1979fc4e9083dfc5d323c9e5 to your computer and use it in GitHub Desktop.
Save Wilfred/ad309ecb1979fc4e9083dfc5d323c9e5 to your computer and use it in GitHub Desktop.
class Parent(object):
def __init__(self):
# I inherit from object, so I don't need to call:
# super().__init__()
# right? If Python only had single inheritance, that would be
# true. I could see, statically, what method is next in the
# lookup path.
pass
class Child(Parent):
pass
class FooMixin(object):
def __init__(self):
# Because Parent.__init__ forgets to call super(), this method
# never gets called.
self.x = 0
def foo(self):
# Since __init__ never got run, this will error.
self.x += 1
class SurprisinglyThisDoesntWork(Child, FooMixin):
pass
print("The method lookup ordering for SurprisinglyThisDoesntWork is:")
print(SurprisinglyThisDoesntWork.mro())
instance = SurprisinglyThisDoesntWork()
instance.foo() # boom!
# Output of running this script:
#
# $ python3 inherit.py
# The method lookup ordering for SurprisinglyThisDoesntWork is:
# [<class '__main__.SurprisinglyThisDoesntWork'>, <class '__main__.Child'>, <class '__main__.Parent'>, <class '__main__.FooMixin'>, <class 'object'>]
# Traceback (most recent call last):
# File "inherit.py", line 34, in <module>
# instance.foo() # boom!
# File "inherit.py", line 23, in foo
# self.x += 1
# AttributeError: 'SurprisinglyThisDoesntWork' object has no attribute 'x'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment