Python is wierd!

David Bolen db3l at fitlinxx.com
Thu Jul 27 01:45:00 EDT 2000


Greg Ewing <to_get_my_address at see.my.signature> writes:

> And to answer your question, yes, you can create an instance
> variable at any time simply by executing "instance.name = value".

Which actually leads to an interesting question relating to a point
that I'm curious how others handle.

If I'm going to package up some state (various bits of information)
into a class (aka using one as a structure - data only), one approach
could be to define an empty class:

    class MyInfo:
	pass

and then whenever I need to later:

    newstate = MyInfo()
    newstate.variable = value
    newstate.other_variable = value

and so on.  Or instead, I can be a little more up front in the first
place and do something like:

    class MyInfo:
        def __init__(self):
            self.variable = initial_value
            self.other_variable = initial_value

I find that the latter approach seems cleaner to me in terms of
defining what I'm going to be using the structure for, but in
practical terms unless you want special initialization, there's not a
lot of difference between the two methods I suppose.  And I've even
found myself in one instance going this route but then in an error
path through the code augmenting the structure with another instance
variable or two just for the failure path (boy, that "felt" wierd).

Of course, if you don't fully populate the information, then you have
to be prepared to field NameErrors later on attributes within the
class instance that weren't assigned.

I'm curious what others would think of the two approaches?

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list