Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

September 12, 2012

Making a python Object with attributes, (pythonic? i don't think so)

Pretty neat?
>>> 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'
here's a test of the getatrribute() and setattr() methods of an object.
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))
view raw grandmaster.py hosted with ❤ by GitHub
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.