Coercing classes

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Jun 27 04:31:35 EDT 2000


Eckhard Pfluegel <Eckhard at pfluegel.fsnet.co.uk> writes:

> My question is the following: imagine you have two classes A and B where
> B is derived from A (B is a subclass of A). The object a is assigned to
> an instance of class A:
> 
> a = A()
> 
> Under which conditions on the structure of class B is it possible in
> Python to convert 'a' to an instance of B? In my application, B would
> only have one additional method defined and no additional attributes
> (than defined in A), so that a conversion would make sense.
> Are there any built-in functions for that purpose??

Variables in Python are not types. So if you want a to 'point to' an
object of B, just write

  a = B()

This throws away the A object, and a now is a B object. Perhaps you
also want to carry some state from the A object to the B object, so
you write

  a = B(a.name, a.age, a.citizenship)

(provided an A instance has all these attributes, and that B's
__init__ expects them as arguments). You can write your own conversion function:

def AtoB(a):
  b = B()
  b.name = a.name
  b.age = a.age
  b.citizenship = a.citizenship
  return b

which would allow you to write

  a = AtoB(a)

Or you could make that a method of A, writing

  a = a.toB()

It is also possible to change the class of the A object to B, by
assigning to a.__class__. However, this is rarely what you want.

Regards,
Martin




More information about the Python-list mailing list