我的需求是基于特定的字符串动态实例化一个类。在这里捕捉到的是新类在其他类上有继承。问题是我无法看到代码从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'}
期望
我期待 “得到了在UNIX基类FUNCTION” 要打印错误。输出需要在“GOT IN THE SUPER CLASS FUNCTION”消息之前打印。
你的代码中有多处错误。你永远不会实例化你的类,所以'__init__'都不会被调用。你的“配置”方法也不接受“自我”论证。 – BrenBarn