1

I am having trouble getting the following code to work. The func function should just return the self.test value, but the code doesn't seem to do the job. I want self.test as the default value for the function.

class model():
    def __init__(self):
        self.test=1
    
    def func(self, test=self.test):
        return(test)

model=model()
model.func()
Ku-trala
  • 651
  • 3
  • 9
  • 20

2 Answers2

1

Function default values are evaluated when the function is defined, not every time the function is called without the necessary argument. As such, self is just a name, not the object invoking the function.

Instead, you just need a sentinel, which is a value that you can use at runtime to determine if an argument was passed. Typically, you can use None, though when None is a valid argument, you'll need to choose a different value.

def func(self, test=None):
    if test is None:
        test = self.text
    return test
chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can do it like so:

class model():
    def __init__(self):
        self.test=1
    
    def func(self, test=None):
        # replaces only None test with self.test
        if test is None:
            test = self.test 
        return test 

    def func2(self, test=None):
        # replaces any falsy test with self.test 
        # falsy are [], {}, "", 0, ...
        test = test or self.test

        return test 

model = model()
model.func()

Both disable your ability to supply None as valid value to your function.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69