Skip to content

Instantly share code, notes, and snippets.

@laundmo
Created November 16, 2020 19:25
Show Gist options
  • Save laundmo/71c29ad3cd61106dc406ca6ff58420a1 to your computer and use it in GitHub Desktop.
Save laundmo/71c29ad3cd61106dc406ca6ff58420a1 to your computer and use it in GitHub Desktop.
mixin that allows instances to access other instances attributes directly
class OtherInstancesMixin():
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError as e:
for instance in object.__getattribute__(self, "_related"):
try:
return object.__getattribute__(instance, name)
except AttributeError:
pass
raise e
# USAGE
class OtherA(): # just a test class
def __init__(self, attr):
self.attr_a = attr
class OtherB():# test class 2
def __init__(self, attr):
self.attr_b = attr
class MyClass(OtherInstancesMixin):
def __init__(self, other_a, other_b):
self._related = [other_a, other_b] # needs to be named _related
print(self.attr_b) # instead of self.other_a.attr
test = MyClass(OtherA("hey"), OtherB("Hello World"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment