Using an existing instance as parent

A

André

Hi, I was trying to find a way to set, upon __init__() the parent of a
class to an existing instance. 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]
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.

Any ideas?
 
B

Bruno Desthuilliers

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top