Skip to content


Instead of setting instance attributes within __init__

I want to make sure that instances of my class have a bunch of attributes. This is the way I’ve always done it in the past:


>>> class C(object):
...     def __init__(self):
...         self.a = 1
...         self.b = 2
... 

It gets the job done fine. But when there’s real work to be done in __init__, then I end up with a really long __init__ method with essentially two separate goals. One section does interesting stuff with the parameters passed in, and the other section creates a bunch of attributes.

So now I’m experimenting with setting properties up for my classes like this:


>>> class D(object):
...     @property
...     def a(self):
...         if not hasattr(self, 'a'):
...             self.a  =1
...         return self.a

I like how I’ve moved the instance variables out of __init__, so that my __init__ method can focus entirely on handling the parameters. I’m curious what problems I’m going to have. At first, I thought I would trigger some infinite loop by accessing self.a when inside the property for a, but so far, I haven’t had any problems.

So what is wrong with this approach?

Posted in Programming, Python.

Viewing 21 Comments

 
close Reblog this comment
blog comments powered by Disqus