Is it possible to use a instance property as a default value ?

George Sakkis george.sakkis at gmail.com
Fri Nov 2 01:59:47 CET 2007


On Nov 1, 4:55 pm, stef mientki <stef.mien... at gmail.com> wrote:
> Chris Mellon wrote:
> > On Nov 1, 2007 3:18 PM, stef mientki <stef.mien... at gmail.com> wrote:
>
> >> hello,
>
> >> I would like to use instance parameters as a default value, like this:
>
> >> class PlotCanvas(wx.Window):
> >>     def __init__(self)
> >>         self.Buf_rp = 0
> >>         self.Buf_wp = 0
>
> >>     def Draw ( self, x1 = self.Buf_rp, x2 = self.Buf_wp ) :
>
> >> is something like this possible ?
>
> > No, because self is not in scope at the time that default arguments
> > are evaluated. The traditional workaround is to use x1=None, and if x1
> > is None: x1 = self.Buf_rp.
>
> thanks Chris,
> I was afraid of that ;-)
>
> cheers,
> Stef


That's the standard approach but if you use it a lot, the recipe at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502206 for
arbitrary default expressions evaluated at call time (rather than
definition time) may come in handy:

class PlotCanvas(wx.Window):
    def __init__(self):
        self.Buf_rp = 0
        self.Buf_wp = 0

    @revaluatable
    def Draw(self, x1 = Deferred('self.Buf_rp'),
                   x2 = Deferred('self.Buf_wp')):
        return (x1,x2)


p = PlotCanvas()
p.Buf_rp = 2
p.Buf_wp = -1
print p.Draw(), p.Draw(x2='foo')


HTH,
George




More information about the Python-list mailing list