Search code examples
python-3.xooppython-class

Overwritting class patametres Python


I want to create class where user declare some attributes and other attributes are calculated on the basis of previously declared parametres.

class Sum:
def __init__(self, a, b):
    self.a = a
    self.b = b
    self.result = None

@property 
def result(self):
    if self.result is None:
        self.result = self.a + self.b
    return self.result

When I declare a and b, result is still None. How can I solve this to calculate result?


Solution

  • In your case, you have declared member and property both at the same time Either of them will work. In your case, if you want the previous results use this code

    class Sum:
        def __init__(self, a, b):
            self.a = a
            self.b = b
            self.output = None
    
        @property
        def result(self):
            if self.output is None:
                self.output = self.a + self.b
            return self.output
    
    
    sum = Sum(1, 2)
    print(sum.result)
    sum.a = 3
    print(sum.result)
    

    will print

    3
    3
    

    Or if you don't want the previous record just want result then use this code

    class Sum:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        @property
        def result(self):
            return self.a + self.b
    
    
    sum = Sum(1, 2)
    print(sum.result)
    sum.a = 3
    print(sum.result)
    
    

    will print

    3
    5