Adding inheritance to a class programmatically in python?

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

Here's what I have so far:

base = list(cls.__bases__)
base.insert(0, ClassToAdd )
base = tuple( base )
cls = type( cls.__name__, base, dict(cls.__dict__) )

      

+2


a source to share


3 answers


Here's an example, using Greg Hugill'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

      

+8


a source


Yes, a type()

built-in function has three forms of arguments that can do this:



type (name, base, dict)

Returns a new object of type. It is essentially a dynamic form of the operator class

. The name string is the name of the class and becomes an attribute __name__

; base tuple lists base classes and becomes an attribute __bases__

; and the dict is the namespace containing the definitions for the class body and becomes an attribute __dict__

.

+4


a source


Another option is not to dynamically change the class hierarchy, but to decorate object instances with new functionality. This is generally cleaner and easier to debug because you only change objects with your code in controls, without having to cross-change your entire class hierarchy.

def extend_object(obj):
    class ExtensionClass(obj.__class__):
        def new_functionality(self):
             print "here"
    obj.__class__ = ExtensionClass

b = Foo()
extend_object(b)
b.new_functionality()
#prints "here"

      

+1


a source







All Articles