Alan McIntyre wrote:
You could do something like this:

blah = type('Struct', (), {})()
blah.some_field = x

I think I'd only do this if I needed to construct objects at runtime based on information that I don't have at compile time, since the two lines of code for your empty class would probably be more recognizable to more people.

Actually, in Python, class definitions are runtime executable statements just like any other. You can do this:


>>> def make_class(with_spam=True):
...  if with_spam:
...   class TheClass(object):
...    def dostuff(self):
...     print 'Spam, spam, spam, spam!'
...  else:
...   class TheClass(object):
...    def dostuff(self):
...     print "I don't like spam!"
...  return TheClass
...
>>> make_class(True)().dostuff()
Spam, spam, spam, spam!
>>> make_class(False)().dostuff()
I don't like spam!

And this:

>>> class Foo(object):
...  num = 3
...  for _ in xrange(14):
...   num *= 1.22
...
>>> Foo.num
48.546607267977542
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to