Skip to content

Instantly share code, notes, and snippets.

@pedroarthur
Created June 12, 2020 01:52
Show Gist options
  • Save pedroarthur/18eb6cb8b0a70c4c2772f55c913ed0ce to your computer and use it in GitHub Desktop.
Save pedroarthur/18eb6cb8b0a70c4c2772f55c913ed0ce to your computer and use it in GitHub Desktop.
Demonstra getitem/setitem
class Getitem(object):
def __init__(self, a):
self.a = a
def __getitem__(self, attr):
print(f"__getitem__ {attr}")
return getattr(self, attr)
class Setitem(Getitem):
def __setitem__(self, attr, value):
print(f"__setitem__ {attr} {value}")
return setattr(self, attr, value)
class Add(object):
def __add__(self, value):
print(f"__add__ {value}")
return self
s = Setitem(Add())
print("s.a access")
s.a += 1
print("s[a] access")
s["a"] += 1
g = Getitem(Add())
print("g.a access")
g.a += 1
print("g[a] access")
g["a"] += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment