1

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.

3
  • Why don't you set sum in change_a_and_b? Commented Nov 27, 2018 at 8:52
  • Because it is ment to be a calculation I use in different function for the same class Commented Nov 27, 2018 at 9:38
  • So? You will always have to use it after you call change_a_and_b... Commented Nov 27, 2018 at 9:49

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Can I still access it like a normal self.variable ?
Yup, exactly like you see in the example (try it out). That's the point of a property, it's a kind of syntactic sugar for treating a function like a variable.
Do I still access it with self.sum or not ?
Yes, you do. self.sum, and not self.sum().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.