28-08-2009 o 20:38:30 xiaosong xia <[email protected]> wrote:
I am trying to define a class with copy constructor as following:
class test:
def __init__(self, s=None):
self=s
x=[1,2]
y=test(x)
print y.__dict__
it gives
{}
The above code doesn't work.
And cannot, as Chris has already written. But it is possible to
customize construction of objects of your class -- using __new__():
[see: http://docs.python.org/reference/datamodel.html#object.__new__ ]
import copy
# in Python 2.x you must explicitly inherit from 'object' type
class Test(object):
"Not tested"
def __new__(cls, s, way=None):
if s is None:
# a new object of 'Test' class
return super(currentclass, cls).__new__(cls, *args)
else:
if way == 'alias':
return s
elif way == 'shallow':
return copy.copy(s)
elif way == 'deep':
return copy.deepcopy(s)
else:
raise ValueError("'way' must be 'alias', "
"'shallow' or 'deepcopy'")
...but in such cases as copying existing objects it is usualy better
(though less romantic :-)) to use an ordinary function (e.g. simply
copy.copy() or copy.deepcopy(), as Gabriel has pointed).
Regards,
*j
--
Jan Kaliszewski (zuo) <[email protected]>
--
http://mail.python.org/mailman/listinfo/python-list