About __init__ and default arguments

Kevin Takacs mr.ribbs at gmail.com
Fri Apr 11 20:20:14 CEST 2008


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



More information about the Python-list mailing list