2

Sometimes when I am designing a new method for a class that needs to act on certain variable, I can't say if it's better to pass this variable as a method parameter or if it's better to save this variable as an instance attribute and just use it inside the method. What are the advantages/disadvantages of both approaches?

class A:
    def __init__(self, data):
        self.data = data
    def my_method(self):
        # does something with self.data

Or

class B:
    def my_method(self, data):
        # does something with data

1 Answer 1

1

It depends on all the other things the class may do.

Most generally, what is the abstraction that your class encapsulates?

Does it need data for lots of operations, or only this? Will data change? If data is the "point" of this class, then it should probably be in the __init__, but if it uses data to act on the object, then probably not.

We need to know more....

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

Comments

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.