fork download
  1. class RevealAccess(object):
  2. """A data descriptor that sets and returns values
  3. normally and prints a message logging their access.
  4. """
  5.  
  6. def __init__(self, initval=None, name='var'):
  7. self.val = initval
  8. self.name = name
  9.  
  10. def __get__(self, obj, objtype):
  11. print('Retrieving', self.name)
  12. return self.val
  13.  
  14. def __set__(self, obj, val):
  15. print('Updating', self.name)
  16. self.val = val
  17.  
  18. class MyClass(object):
  19. x = RevealAccess(10, 'var "x"')
  20. y = 5
  21.  
  22. m = MyClass()
  23.  
  24. print(m.x)
  25.  
  26. m.x = 20
  27.  
  28. print(m.x)
  29. print(m.y)
Success #stdin #stdout 0.04s 9416KB
stdin
Standard input is empty
stdout
Retrieving var "x"
10
Updating var "x"
Retrieving var "x"
20
5