Where is the best place to declare variables in a Python class?

When I write a class, I declare some variables in the method __init__and some others in other functions. So, I usually get 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 method a bit dirty because it is difficult to keep track of all the variables. In contrast, managing variables when they are declared in a method __init__becomes easier. Thus, 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 that declaring all variables of all class functions in a method __init__would be best practice?

+4
source share
2

:

  • , , .
  • , .
  • , .
+4

sum , , ( ). @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

+5

All Articles