Extension without sub-classing?

Andrew Bennetts andrew-pythonlist at puzzling.org
Tue Jun 3 04:29:56 CEST 2003


On Tue, Jun 03, 2003 at 02:17:35AM +0000, Martin d'Anjou wrote:
> Is it possible to extend a python class without sub-classing?
> 
> For example, in file1.py
> 
> class car:
>    def start_engine(self):
>       print "Started"
> 
> And in file2.py, continue the declaration of the car class, without 
> specializing it:
> 
> extend car:
>    def apply_breaks(self):
>       print "You have stopped"
> 
> I know the "extend" syntax is wrong, but I want to extend "car" without 
> sub-classing. Is this possible and how?

You can't directly, but you can do:

    from file1 import car

    def apply_breaks(self):
        print "You have stopped"
    car.apply_breaks = apply_breaks

Or, perhaps more conveniently, you could extend this to:

    from file1 import Car
    
    class CarContinued:
        def apply_breaks(self):
            print "You have stopped"
        # ...etc...

    Car.__dict__.update(CarContinued.__dict__)

-Andrew.






More information about the Python-list mailing list