Skip to content

Instantly share code, notes, and snippets.

@Guilouf
Last active October 25, 2018 08:33
Show Gist options
  • Save Guilouf/48aca1a2fe9b1642f8c88905429f03bd to your computer and use it in GitHub Desktop.
Save Guilouf/48aca1a2fe9b1642f8c88905429f03bd to your computer and use it in GitHub Desktop.
Instance inheritance trial
class Agro:
def __init__(self, parent, prop1=None, prop2=None):
self.parent = parent
self._prop1 = prop1
self._prop2 = prop2
@property
def prop1(self):
try:
if self._prop1 is None:
return self.parent.prop1
else:
return self._prop1
except AttributeError as e:
return None
@property
def prop2(self):
try:
if self._prop2 is None:
return self.parent.prop2
else:
return self._prop2
except AttributeError as e:
return None
ag = Agro(None, prop1="nada")
ag2 = Agro(ag, prop1="nada2")
ag3 = Agro(ag2, prop2="youhou")
ag4 = Agro(ag3)
print(ag.prop1, ag.prop2, ag.__dict__)
print(ag2.prop1, ag2.prop2, ag2.__dict__)
print(ag3.prop1, ag3.prop2, ag3.__dict__)
print(ag4.prop1, ag4.prop2, ag4.__dict__)
# nada None {'parent': None, '_prop1': 'nada', '_prop2': None}
# nada2 None {'parent': <__main__.Agro object at 0x7fe08f87ccf8>, '_prop1': 'nada2', '_prop2': None}
# nada2 youhou {'parent': <__main__.Agro object at 0x7fe08f87cd30>, '_prop1': None, '_prop2': 'youhou'}
# nada2 youhou {'parent': <__main__.Agro object at 0x7fe08f87cd68>, '_prop1': None, '_prop2': None}
ag3._prop2 = "yaya" # the changes are repercuted dynamically, no copies are made
print(ag4.prop1, ag4.prop2, ag4.__dict__)
# nada2 yaya {'parent': <__main__.Agro object at 0x7fe08f87cd68>, '_prop1': None, '_prop2': None}
@Guilouf
Copy link
Author

Guilouf commented Oct 25, 2018

Lorsque l'on fait une copie simple, du style self.prop1 = self.parent.prop1, vu que c'est dans une instance de classe ce n'est pas par référence mais bien par valeur. Du coup lorsque l'on modifie le parent ca n'a pas d'inpact sur l'enfant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment