我的需求是基於特定的字符串動態實例化一個類。在這裏捕捉到的是新類在其他類上有繼承。問題是我無法看到代碼從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