__bases__ does not work! What's next?

The following code does not work in Python 3.x, but it worked with old classes:

class Extender: def extension(self): print("Some work...") class Base: pass Base.__bases__ += (Extender,) Base().extension() 

The question is simple: How to add a superclass dynamically (at run time) to a class in Python 3.x?

But I'm ready, the answer will be difficult! )

+7
python multiple-inheritance runtime
source share
2 answers

For me, this is not possible. But you can create a new class dynamically:

 class Extender(object): def extension(self): print("Some work...") class Base(object): pass Base = type('Base', (Base, Extender, object), {}) Base().extension() 
+4
source share

It seems like you can dynamically change Base.__bases__ if Base.__base__ not an object . (By dynamically changing, I mean so that all pre-existing instances that inherit from Base also dynamically change. Otherwise, see Nikolai Kharechko's decision ).

If Base.__base__ is some dummy TopBase class, then assigning Base.__bases__ seems to work:

 class Extender(object): def extension(self): print("Some work...") class TopBase(object): pass class Base(TopBase): pass b=Base() print(Base.__bases__) # (<class '__main__.TopBase'>,) Base.__bases__ += (Extender,) print(Base.__bases__) # (<class '__main__.TopBase'>, <class '__main__.Extender'>) Base().extension() # Some work... b.extension() # Some work... Base.__bases__ = (Extender, TopBase) print(Base.__bases__) # (<class '__main__.Extender'>, <class '__main__.TopBase'>) Base().extension() # Some work... b.extension() # Some work... 

This has been tested to work in Python 2 (for new and old style classes) and for Python 3. I have no idea why this works until it is:

 class Extender(object): def extension(self): print("Some work...") class Base(object): pass Base.__bases__ = (Extender, object) # TypeError: __bases__ assignment: 'Extender' deallocator differs from 'object' 
+3
source share

All Articles