classes vs dicts

Daniel 'Dang' Griffith noemail at noemail4u.com
Mon May 10 08:22:04 EDT 2004


On Fri, 07 May 2004 10:15:11 -0400, Steven Rumbalski
<srumbalski at copper.net> wrote:

>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']

Yes, you're right.  I mis-spoke what I meant.  Maybe this is closer,
"You can't add or remove arbitrary attributes to an instance of a
class... without magic."  What I mean is that with a dictionary, the
keys can come from external/arbitrary data and be added to the
dictionary with a simple assignment:

    d = dict()
    k, v = raw_input(), raw_input()
    d[k] = v
    w = d[k]

You can't do that to classes or instances without some kind of magic.

    class Foo: pass
    foo = Foo()
    k, v = raw_input(), raw_input()
    setattr(foo, k, v)
    w = getattr(foo, k)

Maybe its just me, but I consider getattr/setattr magic (although in
this simple example, they don't appear too magical, so maybe others
wouldn't consider it so).

Still, I think it is an overgeneralization to say that classes are
just syntactic sugar for dictionaries.

    --dang



More information about the Python-list mailing list