[英]Why does this python logic statement behave opposite to my expected behavior?
我在Python解释器中运行以下命令:
some_list = []
methodList = [method for method in dir(some_list) if (callable(getattr(some_list, method)) and (not method.find('_')))]
我想要的是获取特定对象的所有方法名称的列表, 但带有下划线(即__sizeof__
方法除外
这就是为什么我的代码中嵌套了if语句的原因:
if (callable(getattr(some_list, method)) and (not method.find('_')))
但是methodList
的内容是:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__']
确实,这与我的预期正好相反。
不not method.find('_')
仅在method
字符串未能包含字符串'_'
时返回true吗?
请参阅str.find
的文档。
返回找到子字符串sub的字符串中的最低索引,以使sub包含在切片s [start:end]中。 可选参数start和end解释为切片表示法。 如果未找到sub,则返回-1。
如果未找到下划线,则method.find('_')
表达式返回-1,如果以下划线开头,则返回0。 应用not
意味着仅以下划线开头的方法将给出True
(因为not 0
为True
)。
改用'_' not in method
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.