Python类函数作为字典条目

2024-09-24 02:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本来生成给定MySQL查询的Tableau数据提取(.tde)文件。你知道吗

将行写入.tde需要使用set<column_type>(column_no, column_val)函数分别写入每一列。例如,将整数3写入行中的第二列将类似于row.setInteger(1, 3)。将单词“Bob”写到行中的第4列将看起来像row.setCharString(3, 'Bob')。你知道吗

在遍历列时,我希望根据列类型调用正确的set<column_type>()函数。我把这些函数放在字典里:

tde_set_type_function_map = {
    Type.DATE: Row.setDate,
    Type.DATETIME: Row.setDateTime,
    Type.DOUBLE: Row.setDouble,
    Type.CHAR_STRING: Row.setCharString,
    Type.INTEGER: Row.setInteger,

}

for row in mysql:
      # Create new row
    tde_row = Row(table_def)   # Pass the table definition to the constructor
    for colno, col in enumerate(row):
        col_type = table_def.getColumnType(colno)
        setType = tde_set_type_function_map[col_type]
        print setType # e.g. <unbound method Row.setCharString>
        print type(setType) # e.g. <type 'instancemethod'>
        tde_row.setType(colno, col)
    tde_table.insert(tde_row)

tde_row.setType(colno, col)之后,我得到以下错误:

AttributeError: 'Row' object has no attribute 'setType'

我以前在字典中使用过函数,但在它们属于对象时从未使用过。有合适的方法吗?你知道吗


Tags: 函数notypetablecolumncolrowset