Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__bases__ doesn't work! What's next?

The following code doesn't work in Python 3.x, but it used to work with old-style classes:

class Extender:
    def extension(self):
        print("Some work...")

class Base:
    pass

Base.__bases__ += (Extender,)

Base().extension()

Question is simple: How can I add dynamically (at runtime) a super class to a class in Python 3.x?

But I'm ready the answer will be hard! )

like image 475
17 revs, 13 users 59% Avatar asked Jul 07 '10 08:07

17 revs, 13 users 59%


1 Answers

As for me it is impossible. But you can create new class dynamically:

class Extender(object):
    def extension(self):
        print("Some work...")

class Base(object):
    pass

Base = type('Base', (Base, Extender, object), {})
Base().extension()
like image 110
Mykola Kharechko Avatar answered Oct 03 '22 01:10

Mykola Kharechko