Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use class self variable as default class method argument [duplicate]

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
like image 311
Alex Avatar asked Oct 15 '25 04:10

Alex


2 Answers

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?

like image 97
DiCaprio Avatar answered Oct 17 '25 18:10

DiCaprio


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.

like image 44
Julian Camilleri Avatar answered Oct 17 '25 18:10

Julian Camilleri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!