pythonclassoopdefault-valueinstance-variables

Is there any cool way to express `if x is None: x = self.x` in python class?


I'm just studying python OOP, and truly confused when to use self and not.

especially when I want to make a method that defaultly get object instance input and also wanna make it work as a normal method that can get the input of custom parameters, I get somewhat bothersome to type if x is None: x = self.x for all the parameters of the method.

Example is as follows.

from dataclasses import dataclass

@dataclass
class PlusCalculator():
    x: int = 1
    y: int = 2
    result: int = None
    
    def plus(self, x=None, y=None):
        if x is None: x = self.x    ## the bothersome part
        if y is None: y = self.y
        
        result = x + y
        self.result = result        ## also confusing...is it good way?
        
        return result
    
pc = PlusCalculator()
print(pc.plus())
print(pc.plus(4,5))

Is there any good way to use instance variables as default value of function parameter??


Solution

  • A conditional expression is readable, fast, and intuitive-

    x = self.x if x is None else x
    

    Re:

    Is there any good way to use instance variables as default value of function parameter??

    Regarding the setting of self.result- This should be avoided unless you need to access it as an instance variable later. As such you can simplify this to:

    @dataclass
    class PlusCalculator():
        ...
    
        def plus(self, x=None, y=None):
            x = self.x if x is None else x
            y = self.y if y is None else y
            return x + y