1

I have class A that is supposed to inherit class B whose name is not yet known at the time of A being written. Is it possible to declare A not inheriting anything, and add B as the base class during A's instantiation? Example:

First file

class B:
  def __init__(self):
    self.__name = "Class B"

  def name(self):
    return self.__name

Second file

class A:
  def __init__(self):
    self.__name = "Class A"

# At some point here, the appropriate module name and location is discovered
import sys
sys.path.append(CustomModulePath)
B = __import__(CustomModuleName)

magic(A, B) # TODO What should magic() do?

a = A()
print a.name() # This will now print "Class A", since name() is defined in B.
2
  • 2
    Can you explain why you need to do this? Commented Jun 22, 2010 at 14:48
  • In this application I need to manipulate classes based on the application-specific metadata, not by regular class names. Commented Jun 22, 2010 at 15:03

1 Answer 1

2

Yeah, you can accomplish this with metaclasses. It's not the easiest topic to wrap your head around but it'll do the job. There's a Stack Overflow question about them that looks like it has some good information and I also found an IBM article that might help as well. Somewhere in the official Python documentation, there's a section about them but I can't recall exactly where offhand.

Sign up to request clarification or add additional context in comments.

2 Comments

the SO question particularly has an example on how to mess with inheritance, so look there for sure
Looks like metaclasses are exactly what I needed, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.