classes vs dicts

Steven Rumbalski srumbalski at copper.net
Fri May 7 10:15:11 EDT 2004


Daniel 'Dang' Griffith wrote:

> On 06 May 2004 07:22:05 -0400, Heather Coppersmith <me at privacy.net>
> wrote:
> ...
>>In the end (and in the implementation), classes are just syntactic
>>sugar for dictionaries.
>>
>>    object.attribute    is equiv. to    dictionary[ 'key' ]
> 
> I think you're overgeneralizing, or I'm reading overgenerality into
> your response.  I assume you mean that manipulating an instance of a
> class attribute is syntactic sugar for manipulating a single
> dictionary entry?
> 
> You can't arbitrarily add or remove attributes to an instance of a
> class (without using "magic", which kinda puts a major sour in the
> syntactic sugar!).  Classes are not syntactic sugar for dictionaries.
>     --dang

>>> class Foo:
...     def __init__(self):
...             self.x = 'x'
...             self.y = 'y'
...
>>> foo = Foo()
>>> foo.x, foo.y
('x', 'y')
>>> dir(foo)
['__doc__', '__init__', '__module__', 'x', 'y']
>>> foo.z = 'zeeeeee'
>>> del foo.x
>>> foo.y, foo.z
('y', 'zeeeeee')
>>> dir(foo)
['__doc__', '__init__', '__module__', 'y', 'z']


I'm not sure what you mean by magic.  I just used basic python to
"arbitrarily add or remove attributes to an instance".

You can even muck around with classes:

>>> def new_init(self):
...     self.a = 1
...     self.b = 2
...
>>> Foo.__init__ = new_init
>>> bar = Foo()
>>> bar.a, bar.b
(1, 2)
>>> dir(bar)
['__doc__', '__init__', '__module__', 'a', 'b']

-- 
Steven Rumbalski
news|at|rumbalski|dot|com



More information about the Python-list mailing list