Skip to main content
 首页 » 编程设计

python之在 python 中替换 if elif block

2025年05月04日9birdshome

事实证明,这个条件 block 在我的代码中不断重复。还有其他方法可以让我的生活更轻松吗?当然,条件执行的主体不同。

if self.datatype == "string": 
    t = "z" 
elif self.datatype == "double": 
    t = "d" 
elif self.datatype == "number": 
    t = "i" 
elif self.datatype == "blob": 
    t = "z" 
else: 
    raise EntParEx("Unknown datatype" + self.datatype) 

......使用相同条件的更多代码

def emit_cpp_def(self): 
    s = "" 
    e = "" 
    if self.datatype == "string": 
        s += "static const int " + self.lenvar + " = " + self.length + ";" 
        s += "\nchar" 
        e += "[" + self.lenvar + " + 2" + "]" 
    elif self.datatype == "double": 
        s += "double" 
    elif self.datatype == "number": 
        s += "int" 
    elif self.datatype == "blob": 
        s += "char*" 
    else: 
        raise EntParEx("Unknown datatype" + self.datatype) 
 
    s += " " + self.cpp_membername; 
    s += e 
    s += ";" 
    return s; 
 
def emit_cursor_def_code(self): 
    if self.datatype == "blob": 
        return "" 
 
    ret = "nvl(" + self.db_fieldname + ", " 
    #TODO: Add default value loading! 
    if self.datatype == "string": 
        ret += "\' \'" 
    elif self.datatype == "double": 
        ret += "-1.0" 
    elif self.datatype == "number": 
        ret += "-1" 
    else: 
        raise EntParEx("Unknown datatype" + self.datatype) 
    ret += "), " 
    return ret 

编辑: 我认为我需要的是为每种类型运行特定的功能。不幸的是,我不是那么精通 python。那可以吗?即

switch_datatype(function_string(), function_integer(), ...etc) 

这更糟吗?

请您参考如下方法:

如果它是完全相同的条件,将其粘贴到一个方法中并在需要的地方调用它。否则,在某处定义字典并使用您需要的任何一个。

datatypes = {'string': 'z', 'double': 'd', 'number': 'i', 'blob': 'z'} 
t = datatypes[self.datatype] 

您可能会捕获 KeyError 并引发域异常。