Using an existing instance as parent
bruno.42.desthuilliers at websiteburo.invalid
Mon Sep 1 17:08:36 CEST 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, A):
> super(B, self).__init__(args)
> self = args
Rebinding an argument only affect the current namespace.
> self.y = args
> 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):
def __init__(self, *args):
if isinstance(args, A):
x = copy.copy(args.x) # if it's a mutable and you want a copy
x = args
self.y = args
Be sure to carefully read copy's doc.
More information about the Python-list