Type casting a base class to a derived one?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jan 11 13:38:49 CET 2007


Frederic Rentsch:
>    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.

No need to copy attributes:

class Base(object):
    def __init__ (self, x):
        self.x = x

class Derived(Base):
    def __init__ (self, x, y):
        Base.__init__(self, x)
        self.y = y

d = Derived(1, 2)
print d.x, d.y

Bye,
bearophile




More information about the Python-list mailing list