How to 'declare' class attributes?
Alex Martelli
aleaxit at yahoo.com
Sat May 26 13:47:35 EDT 2001
"eloy" <eloy at rabinf50.uco.es> wrote in message
news:Pine.LNX.4.33.0105261726450.14456-100000 at eloy.ayrna.org...
> I have a doubt about what we could call 'programming philosophy'.
> In some other OO languages, attributes of a class must be declared. In
> Python, we can, as far as I know, take different approaches:
Right, since we have no declarations.
"""
1.- to 'declare' (I mean, bind) all of them in the class
definition:
class foo:
bar= None
baz= 1
fubar= None
"""
This does create attributes *OF THE CLASS*. The *CLASS OBJECT*
has these attributes.
"""
2.- to bind them in __init__:
class foo:
def __init__(self):
self.bar= ...
self.baz= ...
self.fubar= ...
"""
This creates attributes *OF THE INSTANCE OBJECT*. An utterly,
completely different situation, like having vs not having 'static'
when declaring something inside a class statement in C++.
"""
3.- _not_ to bind them until needed:
class foo:
...
def xyzzy(...):
self.bar= ...
self.baz= ...
...
def frob(...):
...
self.fubar= ...
"""
Again, instance attributes.
"""
In my opinion, solution 1 needs good design (I mean _previous_
design) and/or good book-keeping to maintain the list of attributes up to
date. Solution 2 seems better, and solution 3 is the worst.
"""
Solutions 1 and 2 address completely different problems, so
how can they be better/worse than each other...?
3 is indeed only rarely needed.
"""
Considering the legibility of Python, and the good documentation
it allows us to create, I want to ask:
What kind of attribute handling (let's call it 'declaration') do
you use?. Is there a 'standard' or 'best' way to keep track of the
attributes in Python classes?.
"""
1 for class attributes (rarely do I create them except in the stack
body), 80% of 2 and 18% of 3 for instance attributes (I mostly
try to create then in __init__ as that is what the reader of the
program will expect, but sometimes this doesn't fit the needs...
the other 2% is when I first bind an instance attribute NOT in
any of its methods:-).
Alex
More information about the Python-list
mailing list