Skip to content

Instantly share code, notes, and snippets.

@eclecticmiraclecat
Created May 31, 2020 11:46
Show Gist options
  • Save eclecticmiraclecat/d692e6ae1dbdd144530a09623762ab91 to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/d692e6ae1dbdd144530a09623762ab91 to your computer and use it in GitHub Desktop.
>>> class Parent:
... def __init__(self, value):
... self.value = value
... def spam(self):
... print('Parent.spam', self.value)
... def grok(self):
... print('Parent.grok')
... self.spam()
...
>>> p = Parent(42)
>>> p.value
42
>>> p.spam()
Parent.spam 42
>>> p.grok()
Parent.grok
Parent.spam 42
>>>
>>> # add new method
...
>>> class Child1(Parent):
... def yow(self):
... print('Child1.yow')
...
>>> c = Child1(42)
>>> c.value
42
>>> c.spam()
Parent.spam 42
>>> c.grok()
Parent.grok
Parent.spam 42
>>> c.yow()
Child1.yow
>>>
>>> # redefine parent spam method
...
>>> class Child2(Parent):
... def spam(self):
... print('Child2.spam', self.value)
...
>>> c2 = Child2(42)
>>> c2.value
42
>>> c2.spam()
Child2.spam 42
>>> c2.grok()
Parent.grok
Child2.spam 42
>>>
>>> # wrap parent spam method
...
>>> class Child3(Parent):
... def spam(self):
... print('Child3.spam')
... super().spam() # Invoking the original spam method
...
>>> c3 = Child3(42)
>>> c3.value
42
>>> c3.spam()
Child3.spam
Parent.spam 42
>>> c3.grok()
Parent.grok
Child3.spam
Parent.spam 42
>>>
>>> # add new attribute to object
...
>>> class Child4(Parent):
... def __init__(self, value, extra):
... self.extra = extra
... super().__init__(value) # self.value = value
...
>>> c4 = Child4(42, 37)
>>> c4.value
42
>>> c4.extra
37
>>>
>>> # more than one parent
...
>>> class Parent2:
... def yow(self):
... print('Parent2.yow')
...
>>> class Child5(Parent, Parent2):
... pass
...
>>> c5 = Child5(42)
>>> c5.spam()
Parent.spam 42
>>> c5.grok()
Parent.grok
Parent.spam 42
>>> c5.yow()
Parent2.yow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment