如何检查函数是否是列表的属性?

时间:2018-05-05 14:44:25

标签: python attributes

所以,我正在尝试检查函数是否是列表的属性。不幸的是,我找不到办法做到这一点。我试过这段代码:

def test():
    return "test"

list = [test]

if hasattr(list, test):
    print("yes")
else:
    print("no")

但这给了我这个错误:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    if hasattr(list, test):
TypeError: hasattr(): attribute name must be string

我想知道一种工作方式,所以如果你知道怎么做,请告诉我。

1 个答案:

答案 0 :(得分:2)

您问的问题是如何阻止hasattr()给您一个TypeError。修复它的方法是在错误消息中:属性名称必须是字符串。因此,如果您这样做,您将不会收到错误消息,但您也不会得到您期望的答案:

>>> hasattr(list,'test')
False

这是因为test是列表的元素,而不是列表的属性。另一方面,如果你这样做:

>>> hasattr(list,'index')
True

您会看到index 属于list的属性,因为您可以

>>> list.index(test)
0

如果您想知道test中是否有list,请使用in

>>> test in list
True

最后,不要调用变量list