Returning an element from a C struct

Skip Montanaro skip at
Tue Mar 19 18:58:32 CET 2002

    Brad> I'm trying to wrap a C structure in a Python class definition and
    Brad> have come upon this problem.

    Brad> class foo:

    Brad>     __init__(self, dat):
    Brad>         self.ptr = gnum_t(dat)

    Brad>     __getattr__(self,name):
    Brad>         try:
    Brad>             return self.__dict__[name]
    Brad>         except:
    Brad>             if name == 'A':
    Brad>                 return self.__dict__['ptr'].A
    Brad>             elif name == 'B':
    Brad>                 return self.__dict__['ptr'].B
    Brad>             elif name == 'C':
    Brad>                 return self.__dict__['ptr'].C
    Brad>             # And many others

How about

    def __getattr__(self,name):
            return self.__dict__[name]
        except KeyError:
            return getattr(self.ptr, name)


Skip Montanaro (skip at -

More information about the Python-list mailing list