Using an existing instance as parent
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon Sep 1 11:08:36 EDT 2008
André a écrit :
> Hi, I was trying to find a way to set, upon __init__() the parent of a
> class to an existing instance.
??? Sorry but I just can't make any sense of this.
> Here is a minimal example of what I'm
> trying to do:
>
> class A(object):
> def __init__(self, x):
> self.x = x
>
> class B(A):
> def __init__(self, *args):
> if not isinstance(args[0], A):
> super(B, self).__init__(args[0])
> else:
> self = args[0]
Rebinding an argument only affect the current namespace.
> self.y = args[1]
>
> b = B(4, 6)
> print 'b:', b.x, b.y, type(b)
>
> a = A(7)
> c = B(a, 3) # Means: please set c parent's using instance "a"
> print 'c:', c.x, c.y, type(c)
>
> This does not work as can be tested. The reason I'm in search for a
> solution in this area is that in our project, "A" is not copy-able (it
> is written using a boost.python binding to a C++ object that does not
> allow copying) - so I can't simply call, inside "B's __init__()", a
> copy constructor for A.
Ok, I think I get the point... When an A instance is passed as first
arg, you'd like to use this instance's state to call super(B).__init__ ?
If so, here's a possible solution (Q&D, to be corrected according to
real use case, etc):
import copy
class B(A):
def __init__(self, *args):
if isinstance(args[0], A):
x = copy.copy(args[0].x) # if it's a mutable and you want a copy
else:
x = args[0]
super(B, self).__init__(x)
self.y = args[1]
Be sure to carefully read copy's doc.
More information about the Python-list
mailing list