python动态调用子类

假设一个父类Book
有若干子类:EnglishBook,ChineseBook,JapaneseBook
对应englishbook.py,chinesebook.py,japanesebook.py




#book.py
class Book():
def __init__(self, foo, bar):
pass


#englishbook.py
class EnglishBook():
def __init__(self, foo, bar):
Book.__init__(self, foo, bar)




BOOK_MAPPING = {'chinese':1L, 'english':2L, 'japanese':3L}
BID_BOOK = dict((BOOK_MAPPING[book], imp.load_source(book.capitalize() + 'Book', os.path.join('.', book+ 'book.py'))) for book in BOOK_MAPPING)


使用时


bid = 1L
book = BOOK_MAPPING[bid]
bcls = getattr(book, book.__name__)

bb = bcls(foo, bar)
展开阅读全文

没有更多推荐了,返回首页