Skip to content

Instantly share code, notes, and snippets.

@horsfallnathan
Created August 12, 2021 03:50
Show Gist options
  • Save horsfallnathan/383800a70975cbd2c54511fb59897088 to your computer and use it in GitHub Desktop.
Save horsfallnathan/383800a70975cbd2c54511fb59897088 to your computer and use it in GitHub Desktop.
Example of class delegation
# Source: https://stackoverflow.com/a/26467767
class Parent(object):
def __init__(self, name, number):
self.name = name
self.number = number
def scream(self):
print('pparent')
class Child(object):
def __init__(self, parent, other):
self.parent = parent
self.other = other
self.name
def scream(self):
print('child')
def __getattr__(self, name):
try:
return getattr(self.parent, name)
except AttributeError as e:
raise AttributeError("Child' object has no attribute '%s'" % name)
p = Parent("Foo", 42)
c = Child(p, "parrot")
print(c.name, c.number, c.other)
p.name = "Bar"
c.scream()
print(c.name, c.number, c.other )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment