-3

There are a bunch of discussions on this kind of issue here, but I did not see anything about how to implement such a function.

Say I have a class Foo() that has a function bar() inside.

The function bar() takes in either no or only one argument. When it takes in nothing, the attribute is set to 2. Else, it is set to whatever the input is. i.e.

In [32]: foo = Foo()
In [33]: foo.bar()
In [34]: foo.a
Out [34]: 2

and

In [32]: foo = Foo()
In [33]: foo.bar(5)
In [34]: foo.a
Out [34]: 5

How do I do this?

2 Answers2

6

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • And it might be great to mention an [infamous caveat with lists](http://docs.python.org/2/tutorial/controlflow.html#default-argument-values) – J0HN Oct 24 '13 at 09:07
  • Thanks! I have read that post before. Now finally I can link it with my question! –  Oct 24 '13 at 09:18
0

You can give parameters a default value. Just define it as a keyword argument:

def bar(self, param=2):
    self.a = param

Hope this helps!

aIKid
  • 26,968
  • 4
  • 39
  • 65