Is it possible to add a base class to an object instance (not a class!) at runtime? Something along the lines of how Object#extend
works in Ruby:
class Gentleman(object):
def introduce_self(self):
return "Hello, my name is %s" % self.name
class Person(object):
def __init__(self, name):
self.name = name
p = Person("John")
# how to implement this method?
extend(p, Gentleman)
p.introduce_self() # => "Hello, my name is John"
Although it's already answered, here is a function:
This dynamically defines a new class
GentlePerson
, and reassignsp
's class to it:Per your request, this modifies
p
's bases, but does not alterp
's original classPerson
. Thus, other instances ofPerson
are unaffected (and would raise anAttributeError
ifintroduce_self
were called).Although it was not directly asked in the question, I'll add for googlers and curiosity seekers, that it is also possible to dynamically change a class's bases but (AFAIK) only if the class does not inherit directly from
object
:Slightly cleaner version: