动态派生python中的类 [英] Dynamically derive a class in python
本文介绍了动态派生python中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
Python dynamic inheritance: How to choose base class upon instance creation?
我希望一个类根据 init 方法中的参数动态选择一个基类.
I want a class to choose a base class on the fly based on a parameter in the init method.
Class A():
#...
Class B():
#...
Class C():
def __init__(self, base_type):
if parent_type == 'A':
#TODO: make C derive A
else:
#TODO: make C derive B
A和B是派生相同基类的库类.
A and B are library classes that derive the same base class.
类似的问题的答案看起来太丑了.
推荐答案
我假设您的意思是父类型的base_type指令.但是以下应该可以工作
I assume you mean base_type insteand of parent type. But the following should work
Class C():
def __init__(self, base_type):
if base_type == 'A':
self.__class__=A
else:
self.__class__=B
可以在此处找到有关此方法的更多详细信息: http://harkablog.com/dynamic -state-machines.html
Some more details on this approach can be found here: http://harkablog.com/dynamic-state-machines.html
这篇关于动态派生python中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文