t551.py 918 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from time import sleep
  2. class A(object):
  3. def __init__(self):
  4. object.__setattr__(self, "x", 42)
  5. def __getattr__(self, attr):
  6. if isinstance(attr, str):
  7. print "attr is a string, as it should be"
  8. print "Getting " + attr
  9. if attr == "y":
  10. return 41
  11. else:
  12. return 43
  13. def __setattr__(self, attr, value):
  14. if isinstance(attr, str):
  15. print "attr is a string, as it should be"
  16. print "Intercepted attempt to set " + attr + " to " + str(value)
  17. a = A()
  18. print "a.x = " + str(a.x)
  19. print "a.y = " + str(a.y)
  20. print "a.z = " + str(a.z)
  21. a.x = 0
  22. print "a.x = " + str(a.x)
  23. a.x += 1
  24. class B(object):
  25. def __getattr__(self, attr):
  26. sleep(0.01)
  27. return object.__getattr__(self, attr)
  28. def __setattr__(self, attr, value):
  29. sleep(0.01)
  30. return object.__setattr__(self, attr, value)
  31. b = B()
  32. b.x = 42
  33. print "b.x = " + str(b.x)
  34. b.x += 1
  35. print "b.x = " + str(b.x)