copy construtor question
Jan Kaliszewski
zuo at chopin.edu.pl
Sat Aug 29 22:25:45 EDT 2009
28-08-2009 o 20:38:30 xiaosong xia <xiaosongxia at yahoo.com> 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) <zuo at chopin.edu.pl>
More information about the Python-list
mailing list