"literal" objects

Oren Tirosh oren-py-l at hishome.net
Thu Dec 25 06:14:13 EST 2003


On Wed, Dec 24, 2003 at 08:09:31AM +0000, Moosebumps wrote:
...
> A thought that occured to me is that classes are implemented as dictionaries
> (correct?).  So you could have a dictionary like this:
> 
> x = {'a': 3, 'b': 5}
> y = {'a': 5, 'b': 15}
> 
> This would be the __dict__ attribute of an object I suppose.  But I don't
> see anyway to assign it to a variable so you could access them like x.a and
> y.a.  I don't know if this would be a "nice" way to do it or not.

You can update an object's __dict__ from an existing dictionary:

obj.__dict__.update(x) would make obj.a==3 and obj.b==5

You can do this in an object's constructor and combine it with keyword 
arguments to get a nifty struct-like class:

class Struct:
  def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

>>> x=Struct(a=5, b=5)
>>> x.a
5
>>> x.b
5
>>> x

If you want something a bit more fancy, you can add the following __repr__ 
method to the Struct class, so you can now print these structs, too:

  def __repr__(self):
    return "%s(%s)" % (self.__class__.__name__,
      ', '.join(['%s=%s' % (k, repr(v)) for k,v in self.__dict__.items()]))
		  
>>> x
Struct(a=5, b=5)
>>> class Person(Struct):
...   pass
...
>>> p = Person(name="Guido van Rossum", title="BDFL")
>>> p
Person(name='Guido van Rossum', title='BDFL')
>>> p.name
'Guido van Rossum'
>>> p.pet = 'dead parrot'
>>> p
Person(pet='dead parrot', name='Guido van Rossum', title='BDFL')
>>>

    Oren





More information about the Python-list mailing list