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

EMi*_*ler 2 python boolean-logic if-statement python-2.x

我在Python解释器中运行以下代码:

  some_list = []
  methodList = [method for method in dir(some_list) if (callable(getattr(some_list, method)) and (not method.find('_')))]
Run Code Online (Sandbox Code Playgroud)

我想要的是获得特定对象的所有方法名称的列表,除了用下划线命名的方法,即__sizeof__

这就是我在上面的代码中嵌套if语句的原因:

 if (callable(getattr(some_list, method)) and (not method.find('_')))
Run Code Online (Sandbox Code Playgroud)

但内容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 '_'吗?

Mar*_*ers 6

请参阅文档str.find.

返回找到substring sub的字符串中的最低索引,这样sub包含在切片s [start:end]中.可选参数start和end被解释为切片表示法.如果未找到sub,则返回-1.

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

'_' not in method改用.

  • 更好的是''_'不在方法中 (3认同)