【发布时间】:2017-09-18 21:18:30
【问题描述】:
我的要求是根据特定字符串动态实例化一个类。这里的问题是新类继承了其他一些类。问题是我无法看到从 Inherited 类执行的代码。
我试图通过创建一个 SystemConfigure 的类来做到这一点,它将根据字典中给出的参数调用特定的类。在我的代码中,我动态调用从Base 类继承函数的超类。我没有看到 Base 类中的代码被执行。
请告诉我如何做到这一点。
代码
class SystemConfigure():
def __init__(self,snp_dict):
dict = snp_dict
osname = dict['osname']
protocol = dict['protocol']
module = protocol
func_string = osname + "_" + protocol + "_" + "Configure"
print ("You have called the Class:", module, "and the function:", func_string)
m = globals()[module]
func = getattr(m, func_string)
func(dict)
class Base():
def __init__(self):
pass
print("BASE INIT")
def Unix_Base_Configure(dict):
print ("GOT IN THE UNIX BASE CLASS FUNCTION")
def Linux_Base_Configure(dict):
print("GOT IN THE LINUX BASE CLASS FUNCTION")
class Super(Base):
def __init__(self):
dict = dict
Base.__init__(self)
Base.Unix_Base_Configure(dict)
def Unix_Super_Configure(dict):
print ("GOT IN THE UNIX SUPER CLASS FUNCTION", dict)
n = SystemConfigure({'protocol':'Super','osname':'Unix','device':'dut'})
输出
You have called the Class: Super and the function: Unix_Super_Configure
GOT IN THE UNIX SUPER CLASS FUNCTION {'protocol': 'Super', 'osname': 'Unix', 'device': 'dut'}
期待
我期待打印“GOT IN THE UNIX BASE CLASS FUNCTION”错误。需要在“GOT IN THE UNIX SUPER CLASS FUNCTION”消息之前打印输出。
【问题讨论】:
-
您的代码有多个错误。你永远不会实例化你的类,所以
__init__也不会被调用。您的“配置”方法也不接受self参数。
标签: python python-3.x inheritance dynamic