be*******@aol.com wrote:
I have started using classes with Python and have a question
about their use.
In Python, 'attributes are all "public" and "virtual" in C++
terms; they're all accessible everywhere and all looked up
dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
p367). It seems to me that two good conventions are to
(1) initialize all attributes in the __init__ function
(2) avoid creating new attributes elsewhere that are not initialized in
__init__
I have not followed these conventions so far, and sometimes
it is difficult for me to tell what attributes an instance of
a class has. Are these conventions good?
I actually go a very different way. Use properties/descriptors for
everything, with the properties declared directly in the class
definition something like so:
class SessionImporter( sessiondata.SessionData ):
"""Holder for importing data with an interactive session
Primary purpose of this class is to provide a way to safely
store partially-constructed records which may reference either
database-resident records, or other partially-constructed
records.
"""
sourceText = common.StringProperty(
"sourceText", """Source of the data being imported""",
defaultValue = "",
)
newObjectID = common.IntegerProperty(
"newObjectID", """Sequence for the newObjectID of newly created
objects""",
defaultValue = 0,
)
newObjects = common.DictionaryProperty(
"newObjects", """New objects, indexed by newObjectID""",
)
rootObjects = common.ListProperty(
"rootObjects", """IDs for each root-object to be stored""",
)
and then use generic __init__ and the like that can take any set of
specified properties. This way each attribute is fully documented, can
have intelligently calculated defaults, can be initialised anywhere,
etceteras, but there's not the huge collections of boilerplate
initialisation, copying, etceteras code that's needed with bare
attributes. The fact that it also allows for type-checking and
coercian, and generic code for working with properties, is a nice
side-effect :)
There's still the possibility of having properties without values, but
if that's undesired, just declare each with the default of None or "" or
whatever you like *for that particular property*.
Have fun,
Mike
_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/