为什么这个python逻辑语句的行为与我预期的行为相反?
我在Python解释器中运行以下命令:为什么这个python逻辑语句的行为与我预期的行为相反?,python,if-statement,boolean-logic,python-2.x,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('_')))] 我想得到的是一个特定对象的所有方法名称的列表,除了用下划线命名的方法,即\uuuuuuuuizeof\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
some_list = []
methodList = [method for method in dir(some_list) if (callable(getattr(some_list, method)) and (not method.find('_')))]
我想得到的是一个特定对象的所有方法名称的列表,除了用下划线命名的方法,即\uuuuuuuuizeof\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
这就是为什么我在上面的代码中嵌套了if语句:
if (callable(getattr(some_list, method)) and (not method.find('_')))
但是methodList
的内容是:
“UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"初始","迭代","新","减少","减少","减少","减少","报告","反转"__“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、“、”、”、“、”、“、”、”、“、”子类钩子”]
事实上,这与我的预期正好相反
不应而不是方法。只有当方法字符串未能包含字符串'
?时,find('''
)才会返回true以获取详细信息
返回找到子字符串sub的字符串中的最低索引,例如sub包含在切片s[start:end]中。可选参数start和end解释为切片表示法。如果未找到sub,则返回-1
表达式method.find(“')
如果未找到下划线,则返回-1,如果以下划线开头,则返回0。应用not
意味着只有以下划线开头的方法才会给出True
(因为not 0
是True
)
使用“not in method”
。最好是“not in method”
@StevenRumbalski:好建议。谢谢!澄清了问题。从perl迁移到python是一个奇怪的世界。我认为如果你试图找到神奇的方法,那么startswith(“''.'''
将比in
好。或者not method.startswith(“”“)
如果要排除魔术方法和私有方法。