Automatically setting class member variables in Python

Viewed 22373

Say, I have the following class in Python

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

Is there any way to simplify this process? Whenever I add a new member to class Foo, I'm forced to modify the constructor.

4 Answers

Python 3.7 provides dataclasses which are helpful in situations like this:

from dataclasses import dataclass


@dataclass
class Foo:
    a: str = None
    b: str = None
    c: str = None

This saves you from having to write out the __init__ method when you just want to store a few attributes.

Gives you a good __repr__ method:

>>> a = Foo()
>>> a
Foo(a=None, b=None, c=None)

If you need to do calculations on a param, you can implement __post_init__.

See also namedtuple:

from collections import namedtuple

Foo = namedtuple('Foo', ['a', 'b', 'c'])

All fields are required with namedtuple though.

>>> a = Foo(1, 2, 3)
>>> a
Foo(a=1, b=2, c=3)
Related