0

(I am trying to learn Python by myself and I am not a native english speaker.)

I need an advice. What is a usual way to pass a variable in OOP from one method to another? Is it better to make a variable an attribute of a instance, to make a helper 'get' function or something else?

1.

class A(object):
    ...

    def a(self):
        self.first = 32
        second = input("Second:")
        return self.first + second

    def b(self):
        return self.first + 1

..or

class A(object):
    ...

    def get_first(self):
        first = 32
        return first

    def a(self):
        first = get_first()
        second = input("Second:")
        return first + second

    def b(self):
        return get_first() + 1

or is there some other usual way?

4
  • Unclear what you're trying to achieve. Commented Mar 24, 2017 at 7:45
  • I am trying to use a variable (created in one method) from one method in other methods. Commented Mar 24, 2017 at 7:48
  • Please be more specific. The common solution should be having additional parameter for method B. Commented Mar 24, 2017 at 7:49
  • 1
    It depends on class and it's usage. If it make sense to store a value as a part of object than you should do it. If it's just some intermediate result that is required just single time than don't keep it within an object and pass it as an argument. Commented Mar 24, 2017 at 7:50

2 Answers 2

1

It depends. The advantage with using a getter method is that, if the field changes, you don't have to change the functions using it. However, in Python, there is no point to do that, because of properties. You can start by storing self.first as a variable of the instance. If it changes, you can add a @property named first. Then, all the functions refering to self.first will get it through this getter method instead. So, for python in particular, go with the first option.

Sign up to request clarification or add additional context in comments.

Comments

1

I usually use (1) but make sure self.first is properly defined if you call b before a.

If you use (2), try to make get_first as efficient as possible to avoid computing twice the same thing.

1 Comment

Yes, it's a problem if get_first(), let's say takes an input. I don't want 2 times to take an input.

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.