首页 文章

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

提问于
浏览

10 回答

  • 14

    如果您的方法是"regular"方法而不是 statimethodclassmethod 等 .
    我想出了一点点黑客 -

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

    通过相应地更改 if 条件中的"function",可以将其扩展到其他类型的方法 .
    在python 2.7上测试过 .

  • 0

    假设您想知道与列表类关联的所有方法Just Type以下内容

    print (dir(list))
    

    上面将为您提供列表类的所有方法

  • 53

    请注意,您需要考虑是否需要结果中包含的继承(但未覆盖)的基类方法 . dir()inspect.getmembers() 操作确实包含基类方法,但 __dict__ 属性的使用不包括 .

  • 24
    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页

  • 0

    一个例子(列出 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元组列表 . 第一项是成员的名称,第二项是值 .

    您还可以将实例传递给 getmembers

    >>> parser = OptionParser()
    >>> inspect.getmembers(parser, predicate=inspect.ismethod)
    ...
    
  • 253

    dir(theobject) 方法列出对象的所有字段和方法(作为元组)和inspect模块(作为代码编写),用文档列出字段和方法(在“”中) .

    因为可以在Python中调用所有(甚至字段),所以我不确定是否有内置函数仅列出方法 . 您可能想尝试通过 dir 获得的对象是否为callable .

  • 149

    没有外部库的Python 3.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("__")]
    
  • 12

    试试这个属性 __dict__ .

  • -1

    您还可以从类型中导入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']
    
  • 2

    我知道这是一个旧帖子,但只是写了这个函数,并将留在这里是案件有人绊倒寻找答案:

    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))
    

相关问题