python shell的方法列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1378926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:05:35  来源:igfitidea点击:

list of methods for python shell?

pythonshellinteractive

提问by potlee

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

你已经通过我使用的术语发现我是一个 python n00b。

straight forward question:

直截了当的问题:

How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?

我如何才能像在 ruby​​ 中一样在交互式 python shell 中查看特定对象的方法列表(您可以在 ruby​​ irb 中在对象后面加上“.methods”)?

回答by Alex Martelli

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:

现有答案很好地向您展示了如何获取对象的属性,但没有准确回答您提出的问题——如何获取对象的方法。Python 对象有一个统一的命名空间(与 Ruby 不同,Ruby 的方法和属性使用不同的命名空间)。考虑例如:

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

如您所见,这为您提供了所有属性的名称——包括许多刚刚继承自的特殊方法object、特殊数据属性,例如__class____dict____doc__、每个实例数据属性 ( val)、每个实例可执行属性 ( lam)、以及实际方法。

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 inspectis the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as dirand 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 ismethodand pass it as the second argument of getmembers, to tailor the results to your precise, exact needs.

标准库模块inspect是在 Python 中进行自省的最佳方式:它构建在内置的自省钩子(例如dir和更高级的钩子)之上,为您提供有用、丰富且简单的自省服务。例如,在这里,您会看到只显示了由此类专门设计的实例和类方法——不是静态方法,不是实例属性(无论是否可调用),也不是从object. 如果您的选择性需求略有不同,可以轻松构建您自己的调整版本ismethod并将其作为 的第二个参数传递getmembers,以根据您的精确需求定制结果。

回答by Jon W

dir( object )

dir( object )

will give you the list.

会给你名单。

for instance:

例如:

a = 2
dir( a )

will list off all the methods you can call for an integer.

将列出您可以为整数调用的所有方法。

回答by Jon W

>>> help(my_object)

回答by hj-007

Its simple do this for any object you have created

对您创建的任何对象执行此操作很简单

dir(object)

it will return a list of all the attributes of the object.

它将返回对象的所有属性的列表。

回答by u0b34a0f6ae

Python supports tab completion as well. I prefer my python prompt clean (so no thanks to IPython), but with tab completion.

Python 也支持制表符补全。我更喜欢我的 python 提示干净(所以不用感谢 IPython),但有选项卡完成。

Setup in .bashrc or similar:

在 .bashrc 或类似文件中设置:

PYTHONSTARTUP=$HOME/.pythonrc

Put this in .pythonrc:

把它放在 .pythonrc 中:

try:
    import readline
except ImportError:
    print ("Module readline not available.")
else:
    print ("Enabling tab completion")
    import rlcompleter
    readline.parse_and_bind("tab: complete")

It will print "Enabling tab completion" each time the python prompt starts up, because it's better to be explicit. This won't interfere with execution of python scripts and programs.

每次启动 python 提示时,它都会打印“启用选项卡完成”,因为最好是明确的。这不会干扰 python 脚本和程序的执行。



Example:

例子:

>>> lst = []
>>> lst.
lst.__add__(           lst.__iadd__(          lst.__setattr__(
lst.__class__(         lst.__imul__(          lst.__setitem__(
lst.__contains__(      lst.__init__(          lst.__setslice__(
lst.__delattr__(       lst.__iter__(          lst.__sizeof__(
lst.__delitem__(       lst.__le__(            lst.__str__(
lst.__delslice__(      lst.__len__(           lst.__subclasshook__(
lst.__doc__            lst.__lt__(            lst.append(
lst.__eq__(            lst.__mul__(           lst.count(
lst.__format__(        lst.__ne__(            lst.extend(
lst.__ge__(            lst.__new__(           lst.index(
lst.__getattribute__(  lst.__reduce__(        lst.insert(
lst.__getitem__(       lst.__reduce_ex__(     lst.pop(
lst.__getslice__(      lst.__repr__(          lst.remove(
lst.__gt__(            lst.__reversed__(      lst.reverse(
lst.__hash__           lst.__rmul__(          lst.sort(

回答by Steven Kryskalla

For an enhanced version of dir()check out see()!

如需dir()查看增强版see()

>>> test = [1,2,3]
>>> see(test)
    []    in    +    +=    *    *=    <    <=    ==    !=    >    >=    hash()
    help()    iter()    len()    repr()    reversed()    str()    .append()
    .count()    .extend()    .index()    .insert()    .pop()    .remove()
    .reverse()    .sort()

You can get it here:

你可以在这里得到它:

回答by Stephan202

Others have mentioned dir. Let me make an remark of caution: Python objects may have a __getattr__method defined which is called when one attempts to call an undefined method on said object. Obviously dirdoes not list all those (infinitely many) method names. Some libraries make explicit use of this feature, e.g. PLY(Python Lex-Yacc).

其他人也提到过dir。让我提个警告:Python 对象可能有一个已__getattr__定义的方法,当人们试图在该对象上调用未定义的方法时会调用该方法。显然dir没有列出所有那些(无限多)方法名称。一些库明确使用了这个特性,例如PLY(Python Lex-Yacc)。

Example:

例子:

>>> class Test:
...     def __getattr__(self, name):
...         return 'foo <%s>' % name
...
>>> t = Test()
>>> t.bar
'foo <bar>'
>>> 'bar' in dir(t)
False

回答by Nadia Alramli

Do this:

做这个:

dir(obj)

回答by Ants Aasma

If you want only methods, then

如果你只想要方法,那么

def methods(obj):
    return [attr for attr in dir(obj) if callable(getattr(obj, attr))]

But do try out IPython, it has tab completion for object attributes, so typing obj.<tab>shows you a list of available attributes on that object.

但是请尝试使用 IPython,它具有对象属性的选项卡完成功能,因此键入会obj.<tab>显示该对象的可用属性列表。