Best practice for object attributes?

Michael Sparks michaels at rd.bbc.co.uk
Wed Apr 2 07:20:50 EST 2003


Hello,


If I want to model objects with 3 attributes based on the behaviour of
python 2.2/2.3 I'ved noticed I can use either of the following idioms:

class shrubbery1(object):
   name = None
   knightowner = "ni"
   flowering = False

or:
class shrubbery2(object):
   def __init__(self):
      self.name = None
      self.knightowner = "ni"
      self.flowering = False

In both cases I gain objects which have the same 3 attributes.
Differences between
them I find are:
   * shrubbery1 has 3 class attributes as well, with the initial values
     indicated. This isn't the case with shrubbery2.

     >>> [x for x in dir(shrubbery1) if not x[0] == "_"]
     ['flowering', 'knightowner', 'name']

     >>> [x for x in dir(shrubbery2) if not x[0] == "_"]
     []

   * shrubbery2 has 3 entries added to self.__dict__ which act as the
     attribute stores. This is not the case with shrubbery1.

     >>> shrubbery1().__dict__
     {}
     >>> shrubbery2().__dict__
     {'flowering': False, 'name': None, 'knightowner': 'ni'}


Personally I find the former (shrubbery1) clearer, but I'm posting to
find out what people think is generally the better of the two. Do people
find any inherent advantages to one versus the other? (I note that the
shrubbery1 also makes the names of object attributes available to
metaclasses as well)

Thanks for any comments,


Michael.
-- 
Michael.Sparks at rd.bbc.co.uk    
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.






More information about the Python-list mailing list