BrockenDuck
BrockenDuck

Reputation: 220

Python __init__ without executing a variable

I am looking for a way to init a variable in a class. This variable is dependent of other variables that I init in the same class too. Here is an example.

Class class():
    def __init__()
        self.a = None
        self.b = None
        self.sum = self.a + self.b

    def change_a_and_b()
       self.a = input("a = ")
       self.b = input("b = ")

    def print_sum()
        print(self.sum)

This is a simplified example. In my program self.sum is a complicated calculation which I want to use like a "shortcut" so I don't need to write it a lot of times. The problem is I input the variables after the init function. I just don't want to execute self.sum = self.a + self.b when I run __init__. I think there is a do_thing parameter, but I don't know how to use it.

Upvotes: 1

Views: 75

Answers (1)

cha0site
cha0site

Reputation: 10717

You can make sum a property:

class my_class():
    def __init__(self)
        self.a = None
        self.b = None

    @property
    def sum(self):
        return self.a + self.b

    def change_a_and_b(self)
       self.a = input("a = ")
       self.b = input("b = ")

    def print_sum(self)
        print(self.sum)

Upvotes: 4

Related Questions