About __init__ and default arguments

Arnaud Delobelle arnodel at googlemail.com
Fri Apr 11 20:41:39 CEST 2008


On Apr 11, 7:20 pm, Kevin Takacs <mr.ri... at gmail.com> wrote:
> Hi,
>
> I'd like to assign the value of an attribute in __init__ as the default
> value of an argument in a method.  See below:
>
> class aphorisms():
>     def __init__(self, keyword):
>         self.default = keyword
>
>     def franklin(self, keyword = self.default):
>         return "A %s in time saves nine." % (keyword)
>
> def main():
>     keyword = 'FOO'
>     my_aphorism = aphorisms(keyword)
>     print my_aphorism.franklin()
>     print my_aphorism.franklin('BAR')
>
> if __name__ == "__main__":
>     main()
>
> I get this error:
> def franklin(self, keyword = self.default):
> NameError: name 'self' is not defined
>
> As you might expect, I'd like to get:
> A FOO in time saves nine.
> A BAR in time saves nine.
>
> I suppose I could set the default to a string literal, test for it and if
> true assign the value of self.default to keyword; however, that seems
> clunky.  Any ideas how this could be done along the lines of my proposed
> but faulty code?
>
> Thanks,
> Kevin

The idiom is:

    def franklin(self, keyword=None):
        if keyword is None:
            keyword = self.default

HTH

--
Arnaud




More information about the Python-list mailing list