Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Animal:
- # it has to be created this way
- # because `self.properties = {}` calls __setattr__
- # which uses `self.properties[]` so it calls __getattr__
- # which uses `self.properties[]` so it calls __getattr__ again
- properties = {}
- def __init__(self, **kwargs):
- print("\n RUN: self.properties.update(kwargs)")
- self.properties.update(kwargs)
- #print("\n RUN: self.properties = kwargs")
- #self.properties = kwargs # it calls __setattr__ which calls __getattr__ again and again
- print("\n RUN: self.other = 'Hello World!'")
- self.other = 'Hello World!'
- # --- dictionary ---
- # ie. dog['tail'] = 1
- # ie. print( dog['tail'] )
- def __getitem__(self, key):
- print('DEBUG: __getitem__', key)
- return self.properties[key]
- def __setitem__(self, key, value):
- print('DEBUG: __setitem__', key, value)
- self.properties[key] = value
- # --- attribute ---
- # ie. dog.tail = 1
- # ie. print( dog.tail )
- def __getattr__(self, key):
- print('DEBUG: __getattr__', key)
- #return self.properties.get(key, None)
- return self.properties[key]
- def __setattr__(self, key, value):
- print('DEBUG: __set__', key, value)
- self.properties[key] = value
- # --- property ---
- # ie. dog.color = "silver"
- # ie. print( dog.color )
- @property
- def color(self):
- print('DEBUG: color getter')
- return self.properties
- @color.setter
- def color(self, value):
- print('DEBUG: color setter', value)
- self.properties['color'] = value
- # --- main ---
- dog = Animal(legs=4, tail=1, head=1)
- print("\n RUN: dog.color['new_dog'] = 'Brown'")
- dog.color['new_dog'] = 'Brown'
- print("\n RUN: print(dog.new_dog)")
- print(dog.new_dog)
- print("\n RUN: print(dog['new_dog'])")
- print(dog['new_dog'])
- print("\n RUN: dog['new_dog'] = 'Orange'")
- dog['new_dog'] = 'Orange'
- print("\n RUN: dog.new_dog = 'Blue'")
- dog.new_dog = 'Blue'
- print("\n RUN: dog.color = 'Red'")
- dog.color = 'Red'
- print("\n RUN: print(dog.color)")
- print(dog.color)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement