builtin_hasattr.py 799 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. class A:
  2. var = 132
  3. def __init__(self):
  4. self.var2 = 34
  5. def meth(self, i):
  6. return 42 + i
  7. a = A()
  8. print(hasattr(a, "var"))
  9. print(hasattr(a, "var2"))
  10. print(hasattr(a, "meth"))
  11. print(hasattr(a, "_none_such"))
  12. print(hasattr(list, "foo"))
  13. class C:
  14. def __getattr__(self, attr):
  15. if attr == "exists":
  16. return attr
  17. elif attr == "raise":
  18. raise Exception(123)
  19. raise AttributeError
  20. c = C()
  21. print(hasattr(c, "exists"))
  22. print(hasattr(c, "doesnt_exist"))
  23. # ensure that non-AttributeError exceptions propagate out of hasattr
  24. try:
  25. hasattr(c, "raise")
  26. except Exception as er:
  27. print(er)
  28. try:
  29. hasattr(1, b'123')
  30. except TypeError:
  31. print('TypeError')
  32. try:
  33. hasattr(1, 123)
  34. except TypeError:
  35. print('TypeError')