Home > database >  Overwritting class patametres Python
Overwritting class patametres Python

Time:01-18

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?

CodePudding user response:

You can't have a member called result and a property called result. In this case, you probably do NOT want to cache the result. You just want:

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

    @property
    def result(self):
        return self.a   self.b

s = Sum(3,4)
s.a = 4
print(s.result)

will print 8.

CodePudding user response:

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
  •  Tags:  
  • Related