Random ...
 
December 2017
S M T W T F S
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Tags ...
Links



python+zope++:: whatchamacallit?
Posted at 10.Feb,2006 16:38  Comments 5 / Trackbacks 0 / Like this post!
Technorati tag(s):

I have a class and want to initialize the class instance with the keys and values of a dict.

What is this process called? [1] I don't know If you do, please enlighten me.

Here's the class. And I can have a mytest instance with any attributes base on the dict passed:

 Python 2.3.5 (#1, May 24 2005, 15:52:33)
 Type "copyright", "credits" or "license" for more information.

 IPython 0.7.1 -- An enhanced Interactive Python.
 ?       -> Introduction to IPython's features.
 %magic  -> Information about IPython's 'magic' % functions.
 help    -> Python's own help system.
 object? -> Details about 'object'. ?object also works, ?? prints more.

 In [1]: history
 1: ipmagic("history ")

 In [2]: class mytest:
   ...:     def __init__(self, dict):
   ...:         for k,v in dict.iteritems():
   ...:             self.__dict__[k] = v
   ...:
   ...:     def show(self):
   ...:         print dir(self)
   ...:
   ...:

 In [3]: d = {'name':'me','age':40}

 In [4]: d1 = {'color':'blue','size':'XL'}

 In [5]: x = mytest(d)

 In [6]: x.show()
 ['__doc__', '__init__', '__module__', 'age', 'name', 'show']

 In [7]: x.age
 Out[7]: 40

 In [8]: y = mytest(d1)

 In [9]: y.show()
 ['__doc__', '__init__', '__module__', 'color', 'show', 'size']

 In [10]: y.color, y.size
 Out[10]: ('blue', 'XL')

.. [1] I got this tip from dandearson at #python


Bookmark and Share

Is this entry helpful? Comments/Donate/Click some google ads.  
Trackback is http://myzope.kedai.com.my/blogs/kedai/69/tbping 

Comments
Shorter and faster

def __init__(self, dict):
self.__dict__.update(dict)

Hamish Lawson  at 11.Feb,2006 00:21
what about...

Two alternatives:

class foo:
pass
d = {'a':1, 'b':2}
f = foo()
f.__dict__ = d

Or (untested)

class foo(object):
pass

d = {'a':1, 'b':2}
object.__new__(foo, [] **d)

chris mcdonough  at 11.Feb,2006 09:35
nope...

the __new__ thing doesn't work. but this does:

class foo:
pass

d = {}
import new
new.instance(foo, d)

chris mcdonough  at 11.Feb,2006 09:40
great

thanks guys. i learned something new here.

this is my first time seeing new. need to check out what that is.

but, what is this process called? or is there no special name for it?

kedai  at 11.Feb,2006 11:02
construction?

I think it's just a "degenerate" form of construction.

The Python C API has an equivalent call:

PyInstance_NewRaw(klass, dict);

I doubt that helps with naming, but it's true. ;-)

chris mcdonough  at 11.Feb,2006 13:44
Post a comment