简体   繁体   English

使用getattr获取字符串变量的内容

[英]Get content of a string variable using getattr

I would like to know how to retrieve the content of a string variable so that I can use its value as an argument name in a function. 我想知道如何检索字符串变量的内容,以便可以将其值用作函数中的参数名称。 Here the code: 这里的代码:

import pandas
import jinja2

oDateList = ['2017-03-22','2017-03-23','2017-03-24']
oData = pandas.DataFrame()
oData['Date'] = oDateList
MyTemplate = 'Today is {{ Date }}'
oTemplate = jinja2.Template(MyTemplate)

for oRow in oData.index:
    for oColumn in oData.columns:
        MyTemplateUpdated = oTemplate.render(Date=oData.loc[oRow, oColumn])
        print(MyTemplateUpdated)

It works well and returns: 它运作良好并返回:

Today is 2017-03-22
Today is 2017-03-23
Today is 2017-03-24

I would like to dynamically retrieve the argument name Date= from the dataframe column name oColumn (which is 'Date'). 我想从数据oColumn列名称oColumn (它是“日期”)中动态检索参数名称Date= I thought about using getattr(oColumn, 'something') but did not figure out how to do so. 我考虑过使用getattr(oColumn, 'something')但没有弄清楚该怎么做。

I have also tried str(oColumn) and it returns the error: SyntaxError: keyword can't be an expression 我也尝试过str(oColumn) ,它返回错误: SyntaxError: keyword can't be an expression

Thank you 谢谢

If you want to dynamically set the argument name being sent to a function, you'll need to use kwargs. 如果要动态设置要发送给函数的参数名称,则需要使用kwargs。

render(**{argument_name: argument_value}

So in your case, assuming that oColumn contains the string you wish to be the argument, it would look something like this; 因此,在您的情况下,假设oColumn包含您希望作为参数的字符串,则它将看起来像这样;

render(**{oColumn: oData.loc[oRow, oColumn]})

Let me know if I have misunderstood your intent. 如果我误解了您的意图,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM