Advertisement
furas

Python - getitem/setitem, getattr/setattrib, property

May 2nd, 2017
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. class Animal:
  2.  
  3.     # it has to be created this way
  4.     # because `self.properties = {}` calls __setattr__
  5.     # which uses `self.properties[]` so it calls __getattr__
  6.     # which uses `self.properties[]` so it calls __getattr__ again
  7.     properties = {}
  8.  
  9.     def __init__(self, **kwargs):
  10.         print("\n  RUN: self.properties.update(kwargs)")
  11.         self.properties.update(kwargs)
  12.        
  13.         #print("\n  RUN: self.properties = kwargs")
  14.         #self.properties = kwargs # it calls __setattr__ which calls __getattr__ again and again
  15.        
  16.         print("\n  RUN: self.other = 'Hello World!'")
  17.         self.other = 'Hello World!'
  18.  
  19.     # --- dictionary ---
  20.    
  21.     # ie. dog['tail'] = 1
  22.     # ie. print( dog['tail'] )
  23.    
  24.     def __getitem__(self, key):
  25.         print('DEBUG: __getitem__', key)
  26.         return self.properties[key]
  27.    
  28.     def __setitem__(self, key, value):
  29.         print('DEBUG: __setitem__', key, value)
  30.         self.properties[key] = value
  31.    
  32.     # --- attribute ---
  33.  
  34.     # ie. dog.tail = 1
  35.     # ie. print( dog.tail )
  36.    
  37.     def __getattr__(self, key):
  38.         print('DEBUG: __getattr__', key)
  39.         #return self.properties.get(key, None)
  40.         return self.properties[key]
  41.  
  42.     def __setattr__(self, key, value):
  43.         print('DEBUG: __set__', key, value)
  44.         self.properties[key] = value
  45.        
  46.     # --- property ---
  47.  
  48.     # ie. dog.color = "silver"
  49.     # ie. print( dog.color )
  50.    
  51.     @property
  52.     def color(self):
  53.         print('DEBUG: color getter')
  54.         return self.properties
  55.  
  56.     @color.setter
  57.     def color(self, value):
  58.         print('DEBUG: color setter', value)
  59.         self.properties['color'] = value
  60.  
  61. # --- main ---
  62.  
  63. dog = Animal(legs=4, tail=1, head=1)
  64.  
  65. print("\n  RUN: dog.color['new_dog'] = 'Brown'")
  66. dog.color['new_dog'] = 'Brown'
  67.  
  68. print("\n  RUN: print(dog.new_dog)")
  69. print(dog.new_dog)
  70.  
  71. print("\n  RUN: print(dog['new_dog'])")
  72. print(dog['new_dog'])
  73.  
  74. print("\n  RUN: dog['new_dog'] = 'Orange'")
  75. dog['new_dog'] = 'Orange'
  76.  
  77. print("\n  RUN: dog.new_dog = 'Blue'")
  78. dog.new_dog = 'Blue'
  79.  
  80. print("\n  RUN: dog.color = 'Red'")
  81. dog.color = 'Red'
  82.  
  83. print("\n  RUN: print(dog.color)")
  84. print(dog.color)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement