我有一个python模块,它包含几个(继承的)类。让我们称之为foomod:
class Base(object):
def interface_func(self):
pass
class Child1(Base):
def interface_func(self):
#do something
class Child2(Base):
def interface_func(self):
#do something else
我在另一个脚本中使用它:
from foomod import Child1 as Base
def some_function(*params):
b = Base()
result = b.interface_func()
#....
然后我选择通过cmd参数使其可设置,问题开始于:
if __name__ == "__main__":
args = parse_args() #'ArgumentParser args'
if args.child == 1:
from foomod import Child1 as Base
elif args.child == 2:
from foomod import Child2 as Base
#....
这给我一个执行错误:
...在some_function line XXX
全球名称' Base'未定义
我知道我可以这样做:
wrapper_func(child):
if child == 1:
from foomod import Child1 as Base
#....
while True:
yield Base()
child = wrapper_func(args.child)
#usage
def some_function(*params):
b = next(child)
但这只是感觉很难看...... 有没有更好的解决方案?