My Code :
def __init__(self, format):
self.format = format
def process(self, formatting=self.format)
name 'self' is not defined
c("abc").process() # prints "abc"
c("abc").process("xyz") # prints "xyz"
You can't really define this as the default value, since the default value is set before any instances exist. An easy work-around is to do something like this:
class C: def __init__(self, format): self.format = format def process(formatting=None): formatting = formatting if formatting is not None else self.format print formatting
self.format will only be used if
formatting is equal to
To demonstrate the point of how default values work, see this example:
def mk_default(): print "mk_default has been called!" def myfun(foo=mk_default()): print "myfun has been called." print "about to test functions" myfun("testing") myfun("testing again")
And the output here:
mk_default has been called! about to test functions myfun has been called. myfun has been called.
Notice how mk_default was called only once (and before the function was ever called!)