properties and get/set methods

Jp Calderone exarkun at intarweb.us
Sun Apr 6 08:24:57 CEST 2003


On Sat, Apr 05, 2003 at 11:48:41PM -0500, Mike C. Fletcher wrote:
> Dan Bishop wrote:
> 
> >Timothy Grant <tjg at craigelachie.org> wrote in message 
> >news:<mailman.1049581810.25706.python-list at python.org>...
> > 
> >
> ...
> 
> >>Is it possible to determine which attribute was used to as the trigger 
> >>for the call to setvar() or getvar()? so that set_appropriate_attribute() 
> >>or appropriate_attribute() can set the correct attribute or get the 
> >>correct attribute?
> >>   
> >>
> >
> >Why not just use two different getvar and setvar functions?
> >
> 
> When you're doing generic "framework" level programming, it's just not 
> acceptable to have to define 2 (really 3) new functions for every 
> property.  Compare:

  Indeed not.  So move things around a little:

    def makeSetter(name):
        def set(self, value):
            doGeneric(self, name, value)
            self.__dict__[name] = value
        return set
    def makeGetter(name):
        def get(self):
            doGeneric(self, name)
            return self.__dict__[name]
        return get
    def makeProperty(name):
        return property(makeGetter(name), makeSetter(name))

    class Foo:
        bar = makeProperty('bar')
        baz = makeProperty('baz')

  Logically, the two layers still exist (good thing), but the first is
resolved entirely at class-creation time, nicely negating the efficiency
concerns (good thing).

> [snip]

  Jp

-- 
In the days when Sussman was a novice Minsky once came to him as he sat
hacking at the PDP-6. "What are you doing?" asked Minsky. "I am training a
randomly wired neural net to play Tic-Tac-Toe." "Why is the net wired
randomly?" asked Minsky. "I do not want it to have any preconceptions of how
to play." Minsky shut his eyes. "Why do you close your eyes?" Sussman asked
his teacher. "So the room will be empty." At that moment, Sussman was
enlightened.
 -- 
 up 17 days, 2:00, 5 users, load average: 1.13, 1.17, 1.09





More information about the Python-list mailing list