JasperTack
JasperTack

Reputation: 4447

change the superclass of object in Python

I was reading about reflection in Python and came across this statement:

Structural Reflection. It is possible to modify the set of methods a class offers and the set of field an object has. We can also modify the class an object is instance of, and the set of super-classes a class inherits from.

which is stated on this here.

I tried to implement an example where I can modify the class of an instance in Python:

class Child():
    nmbrMovies = 0
    nmbrBooks  = 3

class Adult():
    nmbrMovies = 2
    nmbrBooks  = 5

class Member(Child):
    pass

where I want to have an instance of the Member class say, xwhich initially inherits from the Child class, thus inheriting the maximum amounts of movies and books that can be rent in a fictional library. When the person/member is becomes an Adult, I would like to simply change the superclass of the member to Adult. I know this is not the trivial way to implement such a structure, but I wanted an example to test this functionality of Python.

Does anybody know if what I am trying to do is possible? Or did I misunderstand that property of Python?

Upvotes: 3

Views: 458

Answers (1)

unutbu
unutbu

Reputation: 879421

class Child():
    nmbrMovies = 0
    nmbrBooks  = 3

class Adult():
    nmbrMovies = 2
    nmbrBooks  = 5

class Member(Child):
    pass

x = Member()

Member starts out inheriting from Child:

print(Member.__bases__)
# (<class __main__.Child at 0xb74a141c>,)

It is possible to change this to Adult:

Member.__bases__ = (Adult,)
print(Member.__bases__)
# (<class __main__.Adult at 0xb74a144c>,)

Now x.nmbrMovies finds Adult.nmbrMovies:

print(x.nmbrMovies)
# 2

It is also possible to change the instance's class. x starts out as an instance of Member:

print(x.__class__)
# __main__.Member

but we can change it to say, Child:

x.__class__ = Child
print(x.nmbrMovies)
# 0

Upvotes: 6

Related Questions