Advertisement
Guest User

Untitled

a guest
May 30th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. class Parent(object):
  2. def __init__(self):
  3. # I inherit from object, so I don't need to call:
  4. # super().__init__()
  5. # right? If Python only had single inheritance, that would be
  6. # true. I could see, statically, what method is next in the
  7. # lookup path.
  8. pass
  9.  
  10.  
  11. class Child(Parent):
  12. pass
  13.  
  14.  
  15. class FooMixin(object):
  16. def __init__(self):
  17. # Because Parent.__init__ forgets to call super(), this method
  18. # never gets called.
  19. self.x = 0
  20.  
  21. def foo(self):
  22. # Since __init__ never got run, this will error.
  23. self.x += 1
  24.  
  25.  
  26. class SurprisinglyThisDoesntWork(Child, FooMixin):
  27. pass
  28.  
  29.  
  30. print("The method lookup ordering for SurprisinglyThisDoesntWork is:")
  31. print(SurprisinglyThisDoesntWork.mro())
  32.  
  33. instance = SurprisinglyThisDoesntWork()
  34. instance.foo() # boom!
  35.  
  36. # Output of running this script:
  37. #
  38. # $ python3 inherit.py
  39. # The method lookup ordering for SurprisinglyThisDoesntWork is:
  40. # [<class '__main__.SurprisinglyThisDoesntWork'>, <class '__main__.Child'>, <class '__main__.Parent'>, <class '__main__.FooMixin'>, <class 'object'>]
  41. # Traceback (most recent call last):
  42. # File "inherit.py", line 34, in <module>
  43. # instance.foo() # boom!
  44. # File "inherit.py", line 23, in foo
  45. # self.x += 1
  46. # AttributeError: 'SurprisinglyThisDoesntWork' object has no attribute 'x'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement