简体   繁体   English

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

[英]Why does this python logic statement behave opposite to my expected behavior?

I run the following in the Python interpreter: 我在Python解释器中运行以下命令:

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

What I would like is to get a list of all the names of methods for a particular object, except methods that are named with underscores, ie __sizeof__ 我想要的是获取特定对象的所有方法名称的列表, 带有下划线(即__sizeof__方法除外

This is why I have the if statement nested in my above code: 这就是为什么我的代码中嵌套了if语句的原因:

 if (callable(getattr(some_list, method)) and (not method.find('_')))

But the contents of methodList are: 但是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__']

Indeed, the precise opposite of what I'm expecting. 确实,这与我的预期正好相反。

Shouldn't not method.find('_') only return true when the method string fails to contain the string '_' ? not method.find('_')仅在method字符串未能包含字符串'_'时返回true吗?

See the documentation for str.find . 请参阅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]. 返回找到子字符串sub的字符串中的最低索引,以使sub包含在切片s [start:end]中。 Optional arguments start and end are interpreted as in slice notation. 可选参数start和end解释为切片表示法。 Return -1 if sub is not found. 如果未找到sub,则返回-1。

The expression method.find('_') returns -1 if an underscore is not found, and 0 if it starts with an underscore. 如果未找到下划线,则method.find('_')表达式返回-1,如果以下划线开头,则返回0。 Applying not means that only methods that start with an underscore will give True (because not 0 is True ). 应用not意味着仅以下划线开头的方法将给出True (因为not 0True )。

Use '_' not in method instead. 改用'_' not in method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM