Structure accessible by attribute name or index

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Mar 17 16:34:33 CET 2010


Wes Santee a écrit :
> I am very new to Python, and trying to figure out how to create an
> object that has values that are accessible either by attribute name,
> or by index.  For example, the way os.stat() returns a stat_result or
> pwd.getpwnam() returns a struct_passwd.
> 
> In trying to figure it out, I've only come across C implementations of
> the above types.  Nothing specifically in Python.  What is the Python
> native way to create this kind of object?

Using the appropriate __magicmethods__ for indexed access and computed 
attributes for the attribute access might be a good solution:

# warning : Q&D implementation, would require some sanity checks.

class IndexedValueDescriptor(object):
     def __init__(self, index):
         self._index = index
     def __get__(self, instance, cls):
         if instance is None:
             return self
         return instance[self._index]
     def __set__(self, instance, value):
         instance[self._index] = value

class Structure(object):
     def __init__(self, value1, value2, value3):
         self._values = [value1, value2, value3]
     def __setitem__(self, index, value):
         self._values[index] = value
     def __getitem__(self, index):
         return self._values[index]
     value1 = IndexedValueDescriptor(0)
     value2 = IndexedValueDescriptor(1)
     value3 = IndexedValueDescriptor(2)




Note that there are probably other solutions... Don't know how 
os.stat_result is implemented, might be worth looking at the source 
code. But anyway : the above should get you started.

> I apologize if this has been widely covered already.   In searching for
> an answer, I must be missing some fundamental concept that is
> excluding me from finding an answer.

Well, that's not really a FAQ AFAICT !-)



More information about the Python-list mailing list