I would like to initialize a method’s parameter with some default value if an explicit value was not passed into the method – something like this:
class Example
def __init__(self, data = self.default_data()):
self.data = data
def default_data():
# ....
return something
I got the error:
NameError: name 'self' is not defined
How do I fix this?
The common idiom here is to set the default to some sentinel value (
Noneis typical, although some have suggestedEllipsisfor this purpose) which you can then check.You might also see an instance of
object()used for the sentinel.This latter version has the benefit that you can pass
Noneto your function but has a few downsides (see comments by @larsmans below). If you don’t forsee the need to passNoneas a meaningful argument to your methods, I would advocate using that.