Adding inheritance to a class programmatically in python?
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
a source to share
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__
.
a source to share
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"
a source to share