Problem using copy.copy with my own class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 24 00:21:15 EDT 2008


En Thu, 24 Apr 2008 00:32:37 -0300, Michael Torrie <torriem at gmail.com>  
escribió:

> Jeffrey Barish wrote:
>> Marc 'BlackJack' Rintsch wrote:
>>> Please simplify the code to a minimal example that still has the  
>>> problem
>>> and *show it to us*.  It's hard to spot errors in code that nobody  
>>> except
>>> you knows.
>>
>> Here it is:
>>
>> import copy
>>
>> class Test(int):
>>     def __new__(cls, arg1, arg2):
>                             ^^^^^^^
> The exception is saying that copy.copy is not providing this 3rd
> argument.  I might be a bit dense, but what would arg2 be for?  Isn't
> arg1 supposed to be the object instance you are copying from?  If so,
> arg2 is superfluous.

I agree. In case arg2 were really meaningful, use __getnewargs__ (see )

import copy

class Test(int):
     def __new__(cls, arg1, arg2):
         return int.__new__(cls, arg1)
     def __init__(self, arg1, arg2):
         self.arg2 = arg2
     def __getnewargs__(self):
         return int(self), self.arg2

py> t = Test(3, 4)
py> print type(t), t, t.arg2
<class '__main__.Test'> 3 4
py> t_copy = copy.copy(t)
py> print type(t_copy), t_copy, t_copy.arg2
<class '__main__.Test'> 3 4

But note that subclassing int (and many other builtin types) doesn't work  
as expected unless you redefine most operations:

py> x = t + t_copy
py> print type(x), x
<type 'int'> 6
py> t += t_copy
py> print type(t), t
<type 'int'> 6

-- 
Gabriel Genellina




More information about the Python-list mailing list