mardi 21 avril 2015

Initialize object properties as class properties first in Python

I have the habit to initialize the properties of an instance of a class in the constructor of that class but, in case the properties are very tight to the class, I also declare them and initialize them to None ([] or some other base value) as properties in the class.

For instance:

 class AClass(object):
      aprop = None

      def __init__(self):
           self.aprop = "avalue"

Which in most of the cases it won't make much of a difference from just doing:

 class AClass(object):

      def __init__(self):
           self.aprop = "avalue"

However, if somebody gets the scope of the AClass will notice that an instance of this class is expected to have an attribute named aprop. I think of it as a placeholder for the property aprop in the class.

This looks to me more as a question of style, but I would like to know whether this is a good practice. Would you recommend it? Is it something common? or should I try to get rid of it?

Aucun commentaire:

Enregistrer un commentaire