Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Existing answers do a good job of showing you how to get the ATTRIBUTES of an object, but do not precisely answer the question you posed -- how to get the METHODS of an object. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces). Consider for example:</p> <pre><code>&gt;&gt;&gt; class X(object): ... @classmethod ... def clame(cls): pass ... @staticmethod ... def stame(): pass ... def meth(self): pass ... def __init__(self): ... self.lam = lambda: None ... self.val = 23 ... &gt;&gt;&gt; x = X() &gt;&gt;&gt; dir(x) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clame', 'lam', 'meth', 'stame', 'val'] </code></pre> <p>((output split for readability)).</p> <p>As you see, this is giving you the names of all attributes -- including plenty of special methods that are just inherited from <code>object</code>, special data attributes such as <code>__class__</code>, <code>__dict__</code> and <code>__doc__</code>, per-instance data attributes (<code>val</code>), per-instance executable attributes (<code>lam</code>), as well as actual methods.</p> <p>If and when you need to be more selective, try:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; [n for n, v in inspect.getmembers(x, inspect.ismethod)] ['__init__', 'clame', 'meth'] </code></pre> <p>Standard library module <code>inspect</code> is the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as <code>dir</code> and more advanced ones) to offer you useful, rich, and simple introspection services. Here, for example, you see that only instance and class methods specifically designed by this class are shown -- not static methods, not instance attributes whether callable or not, not special methods inherited from <code>object</code>. If your selectivity needs are slightly different, it's easy to build your own tweaked version of <code>ismethod</code> and pass it as the second argument of <code>getmembers</code>, to tailor the results to your precise, exact needs.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload