python - 将变量值连接到非字符串代码行

标签 python parameters

我有以下功能:

def source_sheets(sheet_name)
    gc.open(sheet_name).sheet1.get_all_records()

如何参数化“sheet1”,以便任何数字都可以替换 1?事实上,它不是字符串或不在括号内,这一事实确实难倒了我。

最佳答案

IIUC,使用getattr

def source_sheets(sheet_name, sheet_num)
    sheet = getattr(gc.open(sheet_name), 'sheet{}'.format(sheet_num))
    records = sheet.get_all_records()
    # do something with records, for example return it

或者可能

def source_sheets(sheet_name, subsheet)
    sheet = getattr(gc.open(sheet_name), subsheet)
    records = sheet.get_all_records()
    # do something with records, for example return it

子工作表的名称是否可以是 'sheet1''sheet2' 等以外的名称。

关于python - 将变量值连接到非字符串代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485186/

相关文章:

python - 如何检查文本文件中的行是否等于特定字符串?

matlab - 将几个 'Name, Value' 参数传递给 MATLAB 函数

javascript - 重定向到页面并传递文本和图像参数 - HTML JS

c - 根据输入向函数发送参数

c - 为什么程序使用-2147483648 -1运行?

powershell - 有没有一种简单的方法可以将特定的 *named* PowerShell 参数直接传递给被调用的函数?

python - web2py PDF - 我将该代码放在哪里?

python - 无法在 Windows 上处理 python 子进程 stderr

Python:基于暗图像上特定颜色的矩形轮廓(OpenCV)

python - 我应该使用 ndb 结构化属性还是单独的模型来限制我的 GAE 查询。基础数据建模问题。