data strucutures in python

Jeff Petkau jpet at eskimo.com
Thu Sep 21 02:07:36 EDT 2000


Ack! Pay no attention to the evil thing I just posted. This
version makes for much nicer looking client code.

> Kragen Sitaker <kragen at dnaco.net> wrote in message
> news:jlWx5.448$mc3.45617 at news-east.usenetserver.com...
> > I was chatting with a coworker about this today.  He mentioned that C#
> > has a neat way of declaring active properties --- you say something
> > like:
> >
> > class foo {
> >   property lambda {
> >     int get() { code here }
> >     void set() { code here }
> >   };
> > };
> >
> > and then the code in the get and set "methods" will be invoked to
> > implement reading or writing the property "lambda" of any object of the
> > class "foo".


class WithProperties:
    def __getattr__(self,name):
        if name.startswith('get'):
            # don't recurse endlessly!
            raise AttributeError(name)
        return getattr(self,'get'+name)()

    def __setattr__(self,name,value):
        try:
            setfun = getattr(self,'set'+name)
        except AttributeError:
            self.__dict__[name] = value
            return
        setfun(value)


class C(WithProperties):
    def setspam(self,value): print 'setting spam to %s' % (value,)
    def getspam(self): print 'got da spam'

c.spam=3
--> setting spam to 3
c.spam
--> got da spam

--Jeff (jpet at eskimo.com)





More information about the Python-list mailing list