Type casting a base class to a derived one?
Paul McGuire
ptmcg at austin.rr._bogus_.com
Thu Jan 11 09:31:48 EST 2007
"Peter Otten" <__peter__ at web.de> wrote in message
news:eo5bia$re6$00$1 at news.t-online.com...
> Frederic Rentsch wrote:
>
>> If I derive a class from another one because I need a few extra
>> features, is there a way to promote the base class to the derived one
>> without having to make copies of all attributes?
>>
>> class Derived (Base):
>> def __init__ (self, base_object):
>> # ( copy all attributes )
>> ...
>>
>> This looks expensive. Moreover __init__ () may not be available if it
>> needs to to something else.
>
> base_instance = Base(...)
> base_instance.__class__ = Derived
>
> Peter
This will change the class-level behavior of the object, but it wont
automagically populate the instance with any attributes that are
specifically added in Derived's __init__.
class A(object):
def __init__(self,x):
self.x = x
def method(self):
print "I am an A whose x value is", self.x
class B(A):
bb = 1000
def __init__(self,x,y):
super(B,self).__init__(x)
self.y = y
def method(self):
print "I am a B whose x value is", self.x
aobj = A(100)
aobj.method()
aobj.__class__ = B
aobj.method()
print aobj.bb
print aobj.y
prints:
I am an A whose x value is 100
I am a B whose x value is 100
1000
Traceback (most recent call last):
File "dertest.py", line 20, in ?
print aobj.y
AttributeError: 'B' object has no attribute 'y'
But it wouldn't be hard to write a makeBaseIntoDerived method:
def makeAintoB(a,y=0):
a.y = y
a.__class__ = B
-- Paul
More information about the Python-list
mailing list