Is my thinking Pythonic?

Paul Boddie paul at boddie.org.uk
Thu Aug 21 14:44:58 CEST 2008


On 21 Aug, 14:21, Hussein B <hubaghd... at gmail.com> wrote:
> If you have a huge class, you can't figure the instance variables of
> each object.
> So, I created this constructor:
> --
> def __init__(self):
>   self.speed = None
>   self.brand = None
> --
> This way, I can figure the instance variables by just reading the
> __init__ method.
> What do you think of my approach? is it considered Pythonic?

I don't like to use the term "Pythonic", but I think it's reasonable
to initialise the attributes in this way. In effect, what you're doing
is to ensure that the attributes have some well-defined state at each
point in the lifetime of the instance, and I find myself doing this a
lot. My __init__ methods typically consist of any calls to superclass
__init__ methods followed by the explicit initialisation of any
additional attributes defined for the instance in the class.

Some people might advocate not bothering defining the attributes until
they are actually set with some value, but then you have to deal with
situations where the attributes are missing. Generally, handling
missing attributes isn't worth the bother unless you have a large
number of attributes which could only *potentially* be present: a
situation which occurs when wrapping "foreign" libraries, for example,
where properties or use of __getattr__ seem more essential than the
luxury they might otherwise appear to be.

Paul



More information about the Python-list mailing list