从python列表中获取函数名

2024-04-26 00:14:57 发布

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

我正在尝试编写一个函数,它将打印对象的值,但只打印列表中定义的值。你知道吗

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
for alarm in alarms:
    print alarm.name

这将为所有报警返回一个特定值。我想让它以这样一种方式工作,我能够打印列表中定义的所有值。这就是我要做的

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
whitelist = ["name", "metric", "namespace"]
for alarm in alarms:
    print alarm.whitelist[0]

然而,这当然行不通。有什么建议是最好的方法吗?这样我就可以打印白名单中定义的所有内容。你知道吗


Tags: toimport列表定义connectec2connregion
2条回答

您可以使用^{}(注意,您指的是属性,或者可能是方法,而不是函数):

for alarm in alarms:
    for attr in whitelist:
        print getattr(alarm, attr)

getattr接受可选的第三个参数,在attr的情况下找不到默认值,因此可以执行以下操作:

for attr in whitelist:
    print "{0}: {1}".format(attr, getattr(alarm, attr, "<Not defined>"))

您可以使用^{} built-in function。你知道吗

您的代码如下所示:

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
whitelist = ["name", "metric", "namespace"]
for alarm in alarms:
    for attribute in whitelist:
        print(getattr(alarm, attribute))

相关问题 更多 >