13.7 The new Module
(Optional in 1.5.2) The new modules is a low-level module that allows you to
create various kinds of internal objects, such as class objects,
function objects, and other kinds that are usually created by the
Python runtime system. Example 13-7 demonstrates this module.
Note that if you're using 1.5.2, you may have to rebuild Python to use
this module; it isn't enabled by the default on all platforms. In 2.0
and later, however, it's always available.
Example 13-7. Using the new Module
File: new-example-1.py
import new
class Sample:
a = "default"
def _ _init_ _(self):
self.a = "initialised"
def _ _repr_ _(self):
return self.a
#
# create instances
a = Sample()
print "normal", "=>", a
b = new.instance(Sample, {})
print "new.instance", "=>", b
b._ _init_ _()
print "after _ _init_ _", "=>", b
c = new.instance(Sample, {"a": "assigned"})
print "new.instance w. dictionary", "=>", c
normal => initialised
new.instance => default
after _ _init_ _ => initialised
new.instance w. dictionary => assigned
|