You can subclass on the fly. This does not mean that you should. In any case, I will provide a mechanism.
The base attribute in each class indicates an inheritance chain:
class Animal(object): pass class Dog(Animal): pass print Animal.__bases__ print Dog.__bases__
So __bases__ is a tuple with the "basics of inheritance". You can replace this tuple (you cannot "attach to it" or "jump out of it" because it is a tuple and the tuples are immutable). For example, let's say that you have a mixin class that adds functionality to some animal subclasses, but not others:
class Animal(object): pass class Dog(Animal): pass class Cat(Animal): pass class TalkMixin(object): def talk(self): print("I talk like a {0}".format(self.__class__.__name__)) if __name__ == "__main__": dog = Dog() cat = Cat() try: dog.talk() cat.talk() except AttributeError: print("Great - the program raised AttributeError, as expected")
It produces the following output:
Great - the program raised AttributeError, as expected I talk like a Dog As expected, cat.talk() raised AttributeError I talk like a Cat as expected, they can no longer talk
Many people consider MixIn classes to be evil. And they may be right! You can imagine that if you mess up the base attribute, you pretty much destroyed your program. So here it is: you can dynamically change the inheritance of an object, but that doesn’t mean what you should (perhaps abstract classes or an implementation of concepts?)
source share