programmatically define a new variable on the fly

osiris43 at gmail.com osiris43 at gmail.com
Mon Aug 13 14:45:22 EDT 2007


> Anyway, I don´t see the point in this. Why don´t you just use
> something like X['g'] instead?

While it's not what the original author is intending, it seems to me
that dynamically adding fields could be useful when something like a
database schema changed frequently.  For example, a row in a database
might contain data related to a customer and I would think it might be
useful to do something like this (where data is a dictionary created
from the column names and row data):

class Customer:
  def __init__(self, data):
    for col_name, value in data.iteritems():
      setattr(self, col_name, value)

Alternatively, you could just assign the original dictionary to a
field on Customer called data and then access it by key:

class Customer:
  def __init__(self, data):
    self.customerData = data

I'm pretty new to Python so it's entirely possible I'm doing things
the hard way but if you had behavior on a class, I can see where
dynamically creating fields on it would be useful.





More information about the Python-list mailing list