I want to pass a default argument to an instance method using the value of an attribute of the instance:
class C: def __init__(self, format): self.format = format def process(self, formatting=self.format): print(formatting)
When trying that, I get the following error message:
NameError: name 'self' is not defined
I want the method to behave like this:
C("abc").process() # prints "abc" C("abc").process("xyz") # prints "xyz"
What is the problem here, why does this not work? And how could I make this work?
In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.
Here, we say simulate because unlike certain other OOP languages (like C++ and Scala), the Java specification doesn't support assigning a default value to a method parameter.
Where can the default parameter be placed by the user? Explanation : None.
You can't really define this as the default value, since the default value is evaluated when the method is defined which is before any instances exist. The usual pattern is to do something like this instead:
class C: def __init__(self, format): self.format = format def process(self, formatting=None): if formatting is None: formatting = self.format print(formatting)
self.format
will only be used if formatting
is None
.
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 that happened before the function was ever called!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With