从python列表中获取函数名

从python列表中获取函数名,python,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()
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]
然而,这当然行不通。有什么建议是最好的方法吗?这样我就可以打印白名单中定义的所有内容。

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

getattr
采用可选的第三个参数,未找到case
attr
中的默认值,因此您可以执行以下操作,例如:

for attr in whitelist:
    print "{0}: {1}".format(attr, getattr(alarm, attr, "<Not defined>"))
对于白名单中的属性:
打印“{0}:{1}”。格式(attr,getattr(alarm,attr,”))
您可以使用

您的代码如下所示:

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))
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))