Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly declare instance fields in Python

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
like image 461
MightyPork Avatar asked Oct 29 '25 05:10

MightyPork


2 Answers

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
like image 70
jonrsharpe Avatar answered Oct 30 '25 21:10

jonrsharpe


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.

like image 45
John1024 Avatar answered Oct 30 '25 22:10

John1024