Advertisement
Guest User

Descriptor behaviour

a guest
Jan 4th, 2011
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. >>> class descr:
  2. ...   def __get__(self, obj, cls):
  3. ...     if obj is None:
  4. ...       print("Retrieved from class")
  5. ...     else:
  6. ...       print("Retrieved from instance")
  7. ...   def __set__(self, obj, val):
  8. ...     print("Set on instance")
  9. ...   def __delete__(self, obj):
  10. ...     print("Deleted from instance")
  11. ...
  12. >>> class Demo:
  13. ...   attr = descr()
  14. ...
  15. >>> Demo().attr
  16. Retrieved from instance
  17. >>> Demo().attr = 1
  18. Set on instance
  19. >>> del Demo().attr
  20. Deleted from instance
  21. >>> Demo.attr
  22. Retrieved from class
  23. >>> Demo.attr = 1                                                                                
  24. >>> Demo.attr                                                                                    
  25. 1                                                                                                
  26. >>> Demo.attr = descr()                                                                          
  27. >>> Demo.attr                                                                                    
  28. Retrieved from class                                                                            
  29. >>> del Demo.attr
  30. >>> Demo.attr                                                                                    
  31. Traceback (most recent call last):                                                              
  32.   File "<stdin>", line 1, in <module>                                                            
  33. AttributeError: type object 'Demo' has no attribute 'attr'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement