4

When I write a class, I declare a some variables within the __init__ method and some other in the other functions. So, I usually end up with something like this:

class Foo:
    def __init__(self,a, b):
        self.a=a
        self.b=b
    def foo1(self,c, d)
        sum=self.a+self.b+c+d
        foo2(sum)
    def foo2(self,sum)
        print ("The sum is ", sum)

I find this way a bit messy because it gets difficult to keep track of all variables. In contrary, managing variables when they are declared within the __init__ method becomes more easy. So, instead of the previous form, we would have:

class Foo:
    def __init__(self,a, b, c, d, sum):
        self.a=a
        self.b=b
        self.c=c
        self.d=d
        self.sum=sum
    def foo1(self)
        self.sum=self.a+self.b+self.c+self.d
        foo2(self.sum)
    def foo2(self)
        print ("The sum is ", self.sum)

Which one would you choose and why? Do you think declaring all the variables of all functions of the class in the __init__ method would be a better practice?

2
  • 1
    Your foo2(sum) call in Foo.foo1 will not be executed, because you have a return statement on the line above it. Commented Oct 10, 2013 at 9:29
  • @MartijnPieters +1. I removed the "returns" Commented Oct 10, 2013 at 9:33

2 Answers 2

5

Your sum is a good candidate for a computed value i.e. method that acts like class variable (not method). This can be done by @property

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

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

f = Foo(1, 2)
print 'The sum is' + f.sum

http://docs.python.org/2/library/functions.html#property

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

2 Comments

see link in my answer
@alexvassel Probably you should explain your answer more explicitly.
4

There are at least three aspects to this:

  • From a design standpoint your constructor should only define variables, that are used at least in two methods in your class or that convey an essential characteristic of the thing you try to model.
  • From a performance point of view, you should use variables with the smallest scope possible, it saves lookups.
  • Keeping the variables local, keeps the cognitive load low.

2 Comments

So, you should not perform any operations within the constructor other than declaring variables. What about calling other methods of the class from within the constructor?
I'm not saying the constructor should only declare variables, just saying that the variables declared best be essential rather than accidental (e.g. intermediate results, helper vars, etc.).

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.