Add a keyword argument:
def bar(self, value=2):
self.a = value
Here value
defaults to 2
if not explicitly given:
>>> foo = Foo()
>>> foo.bar()
>>> foo.a
2
>>> foo.bar(5)
>>> foo.a
5
Note that the function signature is created once; defaults are stored on the function object. A common mistake is to assume that defaults are evaluated each time you call a function, and that can lead to some surprises:
import datetime
def ham(now=datetime.datetime.now()):
print now
Here now
will be fixed to the moment bar
was imported and Python created the function object:
>>> ham()
2013-10-24 10:20:26.024775
>>> # wait some time
...
>>> ham()
2013-10-24 10:20:26.024775
It gets more surprising still when the default value is mutable:
def eggs(param, value=[]):
value.append(param)
print value
Repeatedly calling eggs(2)
will result in the value
list growing, adding a new value 2
to the list each time you call it:
>>> eggs(2)
[2]
>>> eggs(2)
[2, 2]
>>> eggs(2)
[2, 2, 2]
See "Least Astonishment" and the Mutable Default Argument for a longer discussion about this.