This may be a stupid / trivial question, but I'm confused in this matter.
What is the encouraged (pythonic) way of declaring instance fields - in the constructor, or in the class body itself?
class Foo:
    """ Foo class """
    # While we are at it, how to properly document the fields?
    bar = None
    def __init__(self, baz):
        """ Make a Foo """
        self.bar = baz
OR:
class Foo:
    """ Foo class """
    def __init__(self, baz):
        """ Make a Foo """
        self.bar = baz
It's a matter of expectations. People reading your code will expect that the attributes defined at the top level of the class will be class attributes. The fact that you then always replace them in __init__ will only create confusion. 
For that reason you should go with option 2, defining instance attributes inside __init__. 
In terms of documenting the attributes, pick a docstring style and stick to it; I like Google's, other options include numpy's. 
class Foo:
    """A class for foo-ing bazs. 
    Args:
      baz: the baz to foo
    Attributes:
      bar: we keep the baz around 
    """
    def __init__(self, baz):
        self.bar = baz
To keep it simple, let us define class Foo with a class variable bar:
In [34]: class Foo: bar = 1
Now, observe:
In [35]: a = Foo()
In [36]: a.bar
Out[36]: 1
In [37]: Foo.bar = 2
In [38]: a.bar
Out[38]: 2
A change to Foo.bar affects existing instances of the class.
For this reason, one generally avoids class variables, as opposed to instance variables unless one wants these side-effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With