python - 为什么这个 python 逻辑语句的行为与我的预期行为相反?

标签 python if-statement boolean-logic python-2.x

我在 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 的文档.

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

如果未找到下划线,则表达式 method.find('_') 返回 -1,如果下划线以下划线开头,则返回 0。应用 not 意味着只有以下划线开头的方法才会给出 True(因为 not 0True)。

改为使用 '_' not in method

关于python - 为什么这个 python 逻辑语句的行为与我的预期行为相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238143/

相关文章:

python - 如何以变形/漏勺形式更改标签内容?

python - Django 管理内联表单错误

python - 选择 python pandas 数据框最后两列中包含相同文本的行

java - 括号内的 "and"和 "no"的条件

.net - 我应该始终使用 AndAlso 和 OrElse 运算符吗?

python - Matplotlib:未对齐的颜色条刻度线?

python - 如何只读取python中字符串列表的一部分

language-agnostic - 嵌套和级联if-else有什么区别

c++ - 在 if 语句的条件部分定义变量不允许比较其值。为什么?

python - Python是否支持短路?