About __init__ and default arguments
Steve Holden
steve at holdenweb.com
Fri Apr 11 14:34:36 EDT 2008
Kevin Takacs 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?
>
def franklink(self, keyword=None):
if keyword is None:
keyword = self.keyword
would be the usual way to do it.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list