Converting an instance to a subclass?

Jay O'Connor oconnor at bioreason.com
Fri Feb 16 15:48:34 EST 2001


D-Man wrote:

> #2 could be done in B's __init__ function :
> 
>    class B( A ) :
>        def __init__( self , instance_of_A ) :
>            self.value = instance_of_A.value
>            # ...
> 
>    Then when you want an instance of B, you can create it from the
>    given instance of A.
> 

For conveneience you could add a converter in A

class A:

	def asB (self):
		b = B(self)
		return b


and in B you could do

class B:
	def __init__(self, instanceOfA):
		self.__dict__ = instanceOfA.__dict__

The only problem with adding the covenience method to A is that it makes
A aware of it's subclasses hierarchy, which may not be desireable.

Take care,
Jay O'Connor
joconnor at cybermesa.com



More information about the Python-list mailing list