Best practice for object attributes?

laotseu bdesth at removethis.free.fr
Wed Apr 2 08:57:24 EST 2003


Michael Sparks wrote:
> 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? 

One outstanding advantage of the second 'idiom' is that it's the right 
way to define *instance* attributes !-) (which is probably what your 
looking for)

With the first form you get *class* attributes. Make 2 instances of 
Shrubbery1, change the name of first one to 'Brian', print the name of 
the second one, and then try to understand what is the purpose of the 
'self' argument in methods.

> Thanks for any comments,

You're welcome.

Laotseu






More information about the Python-list mailing list