In learning about Python's data model, I am playing with creating objects from existing objects using the __new__
method. Here are some examples which create new objects of various types:
x = 2; print type(x).__new__(x.__class__)
x = {}; print type(x).__new__(x.__class__)
x = [1,2]; print type(x).__new__(x.__class__)
x = 2.34; print type(x).__new__(x.__class__)
x = '13'; print type(x).__new__(x.__class__)
x = 1.0j; print type(x).__new__(x.__class__)
x = True; print type(x).__new__(x.__class__)
x = (1,2); print type(x).__new__(x.__class__)
However, the following three experiments give me errors:
x = None; print type(x).__new__(x.__class__)
x = lambda z: z**2; print type(x).__new__(x.__class__)
x = object; print type(x).__new__(x.__class__)
The errors are (respectively):
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
TypeError: Required argument 'code' (pos 1) not found
TypeError: type() takes 1 or 3 arguments
Why don't these three examples work? (Note: for the lambda
example it appears that I have to pass in a code fragment when I invoke the __new__
method but I don't know how to do that.) I am using Python 2.6.
Please note that I realize this is not necessarily the way you would want to create new objects in real code, but my purpose is not practical, rather, it is to understand how the low-level object methods work.