Using an existing instance as parent

André andre.dos.anjos at gmail.com
Mon Sep 1 15:16:35 CEST 2008


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?



More information about the Python-list mailing list