Created
August 12, 2021 03:50
-
-
Save horsfallnathan/383800a70975cbd2c54511fb59897088 to your computer and use it in GitHub Desktop.
Example of class delegation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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