Can I use self
parameters in my method definition in python
?
class Test:
def __init__(self, path):
self.path = pathlib.Path(path)
def lol(self, destination=self.path):
x = do_stuff(destination)
return x
I can make def lol(self, destination)
and use it this way test_obj.lol(test_obj.path)
. But is there a way to set default destination arg
to self.path
? The other way posted below(based on this answers), but can I refactor it somehow and make it more elegant? Maybe there is new solution in python3.+ versions.
def lol(self, destination=None):
if destination in None:
destination = self.path
x = do_stuff(destination)
return x
No.
This leads to problems, since self.Path
will probably change over runtime.
But the default arguments are all evaluated at creation time.
Therefore destination will always be a static value which might be different to self.Path
at any point.
EDIT:
see Why are default arguments evaluated at definition time in Python?
How I'd refactor the code:
def func_test(self, destination=None):
return do_stuff(destination or self.path)
The above is the cleanest and riskiest. - a best case scenario where you know the value, and that or
fits in perfectly. - otherwise careless to use it.
Otherwise I would opt for:
def func_test(self, destination=None):
return do_stuff(destination if destination is not None else self.path)
In regards to passing self.property
to a function argument; simply no.
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