Pretty neat?
here's a test of the getatrribute() and setattr() methods of an object.
The danger of objects is from my experience that it can cause uglier less comprehensible code. Generally the same code effect is written using a dictionary and keys with less code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> obj = lambda: None | |
>>> obj.data = 'orange; ' | |
>>> obj.chunk = 'aerrrr' | |
>>> obj.data | |
'orange; ' | |
>>> obj.chunk | |
'aerrrr' | |
# if you don't know at runtime what the attributes will be. | |
# use setattr | |
>>> setattr(obj, 'new_attr', 'my value') | |
>>> obj.new_attr | |
'my value' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
obj_one = lambda: None | |
obj_two = lambda: None | |
obj_three = lambda: None | |
entity_indices = '_0','_1','_2' | |
def crazy_yield(): | |
for i in range(40): | |
yield(i) | |
gen_obj = crazy_yield() | |
def fill_attributes(entity_indices, obj): | |
for attr in entity_indices: | |
setattr(obj, attr, next(gen_obj)) | |
for obj in obj_one, obj_two, obj_three: | |
fill_attributes(entity_indices, obj) | |
for obj in obj_one, obj_two, obj_three: | |
for attr in entity_indices: | |
print(getattr(obj, attr)) |