Cool object trick

Alex Stapleton alexs at advfn.com
Fri Dec 17 04:32:41 EST 2004


Except what if you want to access elements based on user input or something?

you can't do

var = "varA"
obj = struct(varA = "Hello")
print obj.var

and expect it to say Hello to you.

objects contain a __dict__ for a reason :P

 > Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
 > obj.sausages, "and", obj.spam' a lot easier ;-)

then why dont you have a breakfast class? if you have this many 
properties associated with the same thing you might as well stick them 
in a class anyway.

Doran_Dermot at emc.com wrote:
> I rather like it!  I prefer writing obj.spam to obj["spam"]!  I wonder if
> there is a technical downside to this use of Python?
> 
> P.S.
> 
> Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
> obj.sausages, "and", obj.spam' a lot easier ;-)
> 
> -----Original Message-----
> From: python-list-bounces+doran_dermot=emc.com at python.org
> [mailto:python-list-bounces+doran_dermot=emc.com at python.org] On Behalf Of
> Jive
> Sent: 17 December 2004 06:29
> To: python-list at python.org
> Subject: Re: Cool object trick
> 
> Kinda cool.
> 
> It's occured to me that just about everything Pythonic can be done with
> dicts and functions.  Your Obj is just a dict with an alternate syntax.  You
> don't have to put quotes around the keys.  But that's cool.
> 
> 
> class struct(object):
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
> 
> # Indented this way, it looks like a struct:
> obj = struct(  saying = "Nee"
>                    , something = "different"
>                    , spam = "eggs"
>                   )
> 
> print obj.spam
> 
> # Is that really much different from this?
> 
> obj2 = { "saying" : "Nee"
>             , "something" : "different"
>             , "spam" : "eggs"
>            }
> 
> print obj2["spam"]
> 
> 




More information about the Python-list mailing list