Please explain this python for for statement: methodList = [method for a method in the dir (object) directory if called (getattr (object, method))]

I am trying to use introspection to get a list of my objects. I read "Immersion in Python", and the above statement:

methodList = [method for method in dir(object) if callable(getattr(object, method))]

does the trick. The problem is that I have no idea what she is doing. For me, it looks like an extreme shorthand of the cycle, testing and adding items to the list. If I'm right, what part of the instructions does what ?!

In other words, can someone translate it into English.

+3
source share
4 answers

Another way to look at this:

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

The design itself is an understanding of a list with a filter.

: dir(), callable(), getattr(),

+3

Python.

[f(y) for y in z]

f (y) y z. ,

[f(y) for y in z if g(y)]

f (y) y z, g (y) .

,

[method for method in dir(object) if callable(getattr(object,method)]

"" dir (object), getattr (, ) .

+3

, :

methodList = []
for method in dir(object):
  if(callable(getattr(object,method))):
     methodList.append(method)
+2

, :

methodList = [method
              for method in dir(object)
              if callable(getattr(object, method))]

:

  • method ( , method ) object,
  • method (.. ),
  • method

SQL, ( " " ) :

SELECT method
FROM dir(object)
WHERE callable(getattr(object, method))
+2

Source: https://habr.com/ru/post/1795961/


All Articles