我在 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 0
是 True
)。
改为使用 '_' not in method
。
关于python - 为什么这个 python 逻辑语句的行为与我的预期行为相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238143/