Copy construction of class instance object
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Wed May 28 07:24:37 EDT 2003
On Tue, 27 May 2003 20:30:00 GMT, "Bror Johansson" <bjohan at telia.com>
wrote:
>
>"Peter Hansen" <peter at engcorp.com> wrote in message
>news:3ED3C1DE.8EC82FC2 at engcorp.com...
>> Bror Johansson wrote:
>> >
>> > Is there a good/recommended way to emulate the copy constructor
>> > classinstance creation (a la C++) in Python?
>>
>> "import copy" plus an appropriate line or two? See
>> http://www.python.org/doc/2.0/lib/module-copy.html
>
>My try:
>
>import copy
>
>class A(object):
> def __init__(self, ainst):
> self.val = 5
>
>class B(A):
> def __init__(self, ainst):
> self = copy.deepcopy(ainst)
>
Besides what G. Holl said in another thread, notice that you are not
calling A's __init__ so B instances never get the val attribute.
>>> class A(object):
... def __init__(self):
... self.val = 5
...
>>> class B(A):
... def __init__(self):
... pass
...
>>> b = B()
>>> b.val
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'B' object has no attribute 'val'
>>>
In Python super class initializers/constructors/whatever are never
called automatically.
>a = A()
>b= B(a)
>
>print b.val
>
>=> AttributeError: 'B' object has no attribute 'val'
>
HTH, with my best regards,
G. Rodrigues
More information about the Python-list
mailing list