Generate variables at run time?
Irmen de Jong
irmen at NOSPAM-REMOVETHIS-xs4all.nl
Thu Jan 9 16:03:07 EST 2003
Byron Morgan wrote:
> I have been using REXX for years for all my scripting needs. In REXX, I can
> use any string as a variable with no special handling.
Something like that is perfectly possible in Python as well. See below.
> for the curious:
> In REXX, for a similar situation, I use a stem "train", then add the train
> number, then add each attribute as events are reported.
> train. = 0
> train.123 = 1 (value represents the number of cars in train)
> train.123.stat = 1 (0 if stopped, 1 if moving)
> train.123.doors = 1 (1 if closed, 0 if open)
The thing is, Python allows you to add names to the naming context of a
class instance dynamically. This means that (unlike most other languages)
you can create an instance of an 'empty' class, like so:
class Train:
pass
train=Train()
and then populate the object with other objects of your choice:
train.number=655
train.stat=1
train.doors=1
train.carclasses = [1,2,2,1,2,2,1,]
You can dump all attributes again with, for instance:
print vars(train)
Irmen
PS I actually use this trick myself often when I know that I have
a set of variables that are somehow related, but don't really need
the overhead of a full class definition, or when the set of variables
is not known in advance.
More information about the Python-list
mailing list