代码之家  ›  专栏  ›  技术社区  ›  Purrell

如何获取python类中的方法列表?

  •  246
  • Purrell  · 技术社区  · 15 年前
    11 回复  |  直到 6 年前
        1
  •  261
  •   the Tin Man    10 年前

    一个例子(列出 optparse.OptionParser 班级):

    >>> from optparse import OptionParser
    >>> import inspect
    >>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
    [([('__init__', <unbound method OptionParser.__init__>),
    ...
     ('add_option', <unbound method OptionParser.add_option>),
     ('add_option_group', <unbound method OptionParser.add_option_group>),
     ('add_options', <unbound method OptionParser.add_options>),
     ('check_values', <unbound method OptionParser.check_values>),
     ('destroy', <unbound method OptionParser.destroy>),
     ('disable_interspersed_args',
      <unbound method OptionParser.disable_interspersed_args>),
     ('enable_interspersed_args',
      <unbound method OptionParser.enable_interspersed_args>),
     ('error', <unbound method OptionParser.error>),
     ('exit', <unbound method OptionParser.exit>),
     ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
     ...
     ]
    

    注意到 getmembers 返回2元组的列表。第一项是成员的名称,第二项是值。

    您还可以将实例传递给 获取成员 :

    >>> parser = OptionParser()
    >>> inspect.getmembers(parser, predicate=inspect.ismethod)
    ...
    
        2
  •  159
  •   the Tin Man    10 年前

    dir(theobject) 方法列出对象的所有字段和方法(以元组的形式),检查模块(以codeape write的形式)列出字段和方法及其文档(在“”中)。

    因为所有内容(甚至字段)都可能在python中调用,所以我不确定是否有一个内置函数只列出方法。你可能想试试 对象 你通过了 dir callable 或者没有。

        3
  •  60
  •   Derorrist    8 年前

    不带外部库的Python3.x应答

    method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
    

    邓德排除结果:

    method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
    
        4
  •  25
  •   Eugene Bulkin    15 年前

    试试这个酒店 __dict__ .

        5
  •  15
  •   tleb Paul R    8 年前

    您还可以从类型中导入FunctionType,并使用 class.__dict__ :

    from types import FunctionType
    
    class Foo:
        def bar(self): pass
        def baz(self): pass
    
    def methods(cls):
        return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
    
    methods(Foo)  # ['bar', 'baz']
    
        6
  •  12
  •   the Tin Man    10 年前

    请注意,您需要考虑是否希望结果中包含继承(但不重写)的基类中的方法。这个 dir() inspect.getmembers() 操作确实包括基类方法,但是 __dict__ 属性没有。

        7
  •  7
  •   Naresh Joshi    6 年前

    假设您想知道与list类相关联的所有方法 只需键入以下内容

     print (dir(list))
    

    上面将给出list类的所有方法

        8
  •  2
  •   Kara Praveen Prasad    9 年前
    def find_defining_class(obj, meth_name):
        for ty in type(obj).mro():
            if meth_name in ty.__dict__:
                return ty
    

    所以

    print find_defining_class(car, 'speedometer') 
    

    思考python第210页

        9
  •  0
  •   markroxor    6 年前

    如果您的方法是“常规”方法而不是 statimethod , classmethod 等。
    我想出了一个小技巧-

    for k, v in your_class.__dict__.items(): if "function" in str(v): print(k)

    这可以通过更改 if 相应的条件。
    在Python2.7上测试。

        10
  •  0
  •   Josh Dando    6 年前

    这也适用于:

    MyMeult.Py

    def foo(x)
       return 'foo'
    def bar()
       return 'bar'
    

    在另一个文件中

    import inspect
    import mymodule
    method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
    

    输出:

    ['foo', 'bar']
    

    从python文档:

    inspect.isroutine(对象)

    Return true if the object is a user-defined or built-in function or method.
    
        11
  •  -1
  •   the Tin Man    10 年前

    我知道这是一篇老文章,但是刚刚写了这个函数,如果有人在寻找答案时绊倒了,我会把它留在这里:

    def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
    
        def acceptMethod(tup):
            #internal function that analyzes the tuples returned by getmembers tup[1] is the 
            #actual member object
            is_method = inspect.ismethod(tup[1])
            if is_method:
                bound_to = tup[1].im_self
                internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
                if internal and exclude_internal:
                    include = False
                else:
                    include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
            else:
                include = False
            return include
        #uses filter to return results according to internal function and arguments
        return filter(acceptMethod,inspect.getmembers(the_class))