Search code examples
phppythonprototype-oriented

Prototyping-orientated features in Python?


I have written a PHP application and have a problem that I cannot solve in a good way in PHP. So I am thinking over porting it to Ruby or Python--two languages I never used before. As far as I've seen this problem could be solved in Ruby and my question is now if I can solve it in Python, too:

The core of the application has a class A that I want to extend. There is one extension E1 that extends A by a method doFoo and one extension E2 that extends A by a method doBar. Now I want to use both extensions without having to change the code of A, E1 or E2. In PHP this could be archived by writing a third extension E3, that provides a class B that extends A and mixes in E1 and E2 with traits or by some other dirty tricks. But I want to be able to have the core, to have these two extensions and to have the info in the config: "use extensions E1 and E2" without the necessity of any more classes that puts everything together (and without using __call()).

Is that possible in Python in any way? I don't really need prototypes that could be changed during runtime. Every instance of A should have doFoo and doBar.

EDIT: The whole thing should work without extensions, with only E1 (without E2), with only E2 (without E1) and with both extensions.


Solution

  • As mailson suggested, multiple inheritance is the way to go. A simple

    class E(A, E1, E2):
        ...
    

    Should do what you need.

    EDIT: To do it dynamically you can use type:

    E = type("E", (A, E1, E2), {})
    

    EDIT2: Dougal beat me to it :D