list of methods for python shell?

后端 未结 9 1377
鱼传尺愫
鱼传尺愫 2021-02-13 21:27

You\'d have already found out by my usage of terminology that I\'m a python n00b.

straight forward question:

How can i see a list of methods for a particular obj

9条回答
  •  误落风尘
    2021-02-13 21:57

    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:

    >>> 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
    ... 
    >>> x = X()
    >>> 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']
    

    ((output split for readability)).

    As you see, this is giving you the names of all attributes -- including plenty of special methods that are just inherited from object, special data attributes such as __class__, __dict__ and __doc__, per-instance data attributes (val), per-instance executable attributes (lam), as well as actual methods.

    If and when you need to be more selective, try:

    >>> import inspect
    >>> [n for n, v in inspect.getmembers(x, inspect.ismethod)]
    ['__init__', 'clame', 'meth']
    

    Standard library module inspect is the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as dir 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 object. If your selectivity needs are slightly different, it's easy to build your own tweaked version of ismethod and pass it as the second argument of getmembers, to tailor the results to your precise, exact needs.

提交回复
热议问题