"literal" objects

David Bolen db3l at fitlinxx.com
Fri Dec 26 10:25:26 EST 2003


"Francis Avila" <francisgavila at yahoo.com> writes:

> Is this what you consider inelegant?  If it's too over-engineered (!) for
> you, use a more basic data type, like a dict (as you suggest later).  Or you
> can simply bypass init and assign directly:
> 
> x = object()
> x.a = 3
> x.b = 5.0
> 
> But since you *know* the struct's structure, you might as well use __init__
> to formalize it.  And you're still executing object's __init__, anyway.

Another way to accomplish the above but in a declarative way, needn't
even involve the use of __init__ - you could just:

class mystruct:
    a = 3
    b = 5.0

and you're done.  Technically the names 'a' and 'b' are class level,
but they'll work the same way as instance variables unless they are
assigned to (in which case they become local to the instance).  This
also lets you access them as class level if this is really just a
single grouping of data rather than something you want multiple
instances of.

Of course, this code is still being "executed" so that doesn't address
the OP's issue on that front (although IMO that's really a non-issue).

-- David




More information about the Python-list mailing list