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
Trackback is http://myzope.kedai.com.my/blogs/kedai/69/tbping
def __init__(self, dict):
self.__dict__.update(dict)
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)
the __new__ thing doesn't work. but this does:
class foo:
pass
d = {}
import new
new.instance(foo, d)
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?
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. ;-)
