我正在尝试使用内省来获取我的对象函数的列表。我一直在读“潜入Python",上面提到的这句话:
methodList = [method for method in dir(object) if callable(getattr(object, method))]真的很管用。问题是,我不知道它在做什么。对我来说,它看起来像是循环、测试和向列表中添加元素的极端简写。如果我是正确的,那么语句的哪一部分做了什么?!
换句话说,有人能把它翻译成英语吗?
发布于 2011-03-03 15:42:55
另一种看待这个问题的方式:
methodList = []
for method in dir(object): # for every attribute in object
# note that methods are considered attributes
if callable(getattr(object, method)) # is it callable?
methodList.append(method)
return methodList这个结构本身就是一个带有过滤器的列表理解。
请参阅:dir()、callable()、getattr()、list comprehensions
发布于 2011-03-03 15:43:00
这是Python中列表解释的一个例子。
[f(y) for y in z]表示为列表z中的每个元素y创建一个元素列表f(y)。您可以添加一个可选的过滤表达式,给出
[f(y) for y in z if g(y)]这意味着为z中的元素y创建所有元素f(y)的列表,其中g(y)为true。
翻译过来,这给出了
[method for method in dir(object) if callable(getattr(object,method)]意思是在可调用getattr(object,method)的dir(object)中创建所有元素"method“的列表。
发布于 2011-03-03 15:42:28
这是一种列表理解,相当于这样:
methodList = []
for method in dir(object):
if(callable(getattr(object,method))):
methodList.append(method)https://stackoverflow.com/questions/5177919
复制相似问题