Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding inheritance to a class programmatically in python?

Tags:

python

Can I make a class inherit a class "in-program" in Python?

heres what i have so far:

base = list(cls.__bases__)
base.insert(0, ClassToAdd )
base = tuple( base )
cls = type( cls.__name__, base, dict(cls.__dict__) )
like image 423
Timmy Avatar asked Dec 07 '22 03:12

Timmy


2 Answers

Here is an example, using Greg Hewgill's suggestion:

class Foo(object):
    def beep(self):
        print('Hi')

class Bar(object):
    x = 1  

bar = Bar()
bar.beep()
# AttributeError: 'Bar' object has no attribute 'beep'

Bar = type('Bar', (Foo,object), Bar.__dict__.copy())
bar.__class__ = Bar
bar.beep()
# 'Hi'
like image 121
unutbu Avatar answered Dec 09 '22 18:12

unutbu


Yes, the type() built-in function has a three argument form that can do this:

type(name, bases, dict)

Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute.

like image 34
Greg Hewgill Avatar answered Dec 09 '22 17:12

Greg Hewgill