查找 Python 对象有哪些方法
给定任何类型的 Python 对象,是否有一种简单的方法来获取该对象具有的所有方法的列表?
或者,如果这是不可能的,除了检查调用该方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
给定任何类型的 Python 对象,是否有一种简单的方法来获取该对象具有的所有方法的列表?
或者,如果这是不可能的,除了检查调用该方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(22)
可以创建一个 getAttrs 函数,该函数将返回对象的可调用属性
名称
One can create a
getAttrs
function that will return an object's callable property namesThat'd return
将列表作为对象
list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))
你会得到:
Take a list as an object
list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))
You get:
为了在整个模块中搜索特定方法
In order to search for a specific method in a whole module
While "请求宽恕比请求许可更容易" 肯定是 Pythonic 方式,您可能正在寻找:
While "Easier to ask for forgiveness than permission" is certainly the Pythonic way, you may be looking for:
您可以使用 Python 中预定义的 dir()。
您还可以将对象传递给 dir() 作为
如果该对象是预定义类的对象,例如 int、str 等,它会显示其中的方法(您可能知道这些方法是内置函数)。 如果该对象是为用户定义的类创建的,它将显示该类中给出的所有方法。
You can make use of dir() which is pre-defined in Python.
You can also pass an object to dir() as
If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.
例如,如果您使用 shell plus,则可以使用它:
这样,使用 '??' 在您的对象之后,它将显示该类具有的所有属性/方法。
If you are, for instance, using shell plus you can use this instead:
that way, with the '??' just after your object, it'll show you all the attributes/methods the class has.
这是一个很好的单行(但也会获得属性):
Here's a nice one liner (but will get attributes as well):
大多数时候,我想看到用户定义的方法,而不想看到以'__'开头的内置属性,如果您愿意,可以使用以下代码:
例如,对于这个类:
上面的代码将打印:['print_name']
Most of the time, I want to see the user-defined methods and I don't want to see the built-in attributes that start with '__', if you want that you can use the following code:
For example, for this class:
Above code will print: ['print_name']
获取任何对象的方法列表的最简单方法是使用
help()
命令。它将列出与该对象关联的所有可用/重要方法。
例如:
The simplest way to get a list of methods of any object is to use the
help()
command.It will list out all the available/important methods associated with that object.
For example:
除了更直接的答案之外,如果我没有提到IPython,那就是我的失职。
点击 Tab 查看可用的方法,并带有自动完成功能。
一旦找到方法,请尝试:
查看 pydocs、方法签名等。
啊... REPL。
On top of the more direct answers, I'd be remiss if I didn't mention IPython.
Hit Tab to see the available methods, with autocompletion.
And once you've found a method, try:
to see the pydocs, method signature, etc.
Ahh... REPL.
检查它是否有特定的方法:
To check if it has a particular method:
如果您特别想要方法,则应该使用inspect .is方法。
对于方法名称:
对于方法本身:
有时
inspect.isroutine< /code>
也很有用(对于内置函数、C 扩展、没有“绑定”编译器指令的 Cython)。
If you specifically want methods, you should use inspect.ismethod.
For method names:
For the methods themselves:
Sometimes
inspect.isroutine
can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).假设我们有一个 Python
obj
。 然后查看它拥有的所有方法,包括那些由__
包围的方法(神奇方法):要排除魔法内置函数,可以这样做:
Suppose we have a Python
obj
. Then to see all the methods it has, including those surrounded by__
(magic methods):To exclude magic builtins one would do:
这应该有效:)
This should work :)
没有可靠的方法来列出所有对象的方法。
dir(object)
通常很有用,但在某些情况下它可能不会列出所有方法。 根据dir()
文档:< em>“使用参数,尝试返回该对象的有效属性列表。”检查该方法是否存在可以通过
callable(getattr(object, method) 来完成)
正如已经提到的那样。There is no reliable way to list all object's methods.
dir(object)
is usually useful, but in some cases it may not list all methods. According todir()
documentation: "With an argument, attempt to return a list of valid attributes for that object."Checking that method exists can be done by
callable(getattr(object, method))
as already mentioned there.此处指出的所有方法的问题是您无法确定某个方法不存在。
在Python中,您可以通过
__getattr__
和__getattribute__
拦截点调用,从而可以“在运行时”创建方法示例:
如果执行它,则可以调用不存在的 方法对象字典中的方法...
这就是为什么你使用 更容易询问Python 中的宽恕优于许可 范例。
The problem with all methods indicated here is that you can't be sure that a method doesn't exist.
In Python you can intercept the dot calling through
__getattr__
and__getattribute__
, making it possible to create method "at runtime"Example:
If you execute it, you can call non-existing methods in the object dictionary...
And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.
打开 Bash shell(在 Ubuntu 上为 Ctrl + Alt + T)。 在其中启动 Python 3 shell。 创建一个对象来观察其方法。 只需在其后面添加一个点,然后按两次 Tab,您就会看到如下内容:
Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:
我已经完成了以下函数(
get_object_functions
),它接收一个对象(object_
)作为其参数,并返回一个列表(functions
) 包含对象类中定义的所有方法(包括静态方法和类方法):嗯,它只是检查类属性类型的字符串表示形式是否等于
""
或""
,然后将该属性包含在functions
列表中(如果该属性为True< /代码>。
演示
输出
对于代码的更简洁版本: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py
I have done the following function (
get_object_functions
), which receives an object (object_
) as its argument, and returns a list (functions
) containing all of the methods (including static and class methods) defined in the object's class:Well, it just checks if the string representation of the type of a class' attribute equals
"<class 'function'>"
or"<class 'method'>"
and then includes that attribute in thefunctions
list if that'sTrue
.Demo
Output
For a cleaner version of the code: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py
您可以使用内置的 dir() 函数来获取模块具有的所有属性的列表。 在命令行中尝试一下,看看它是如何工作的。
此外,您还可以使用
hasattr(module_name, "attr_name")
函数来查找模块是否具有特定属性。有关详细信息,请参阅 Python 内省。
You can use the built in
dir()
function to get a list of all the attributes a module has. Try this at the command line to see how it works.Also, you can use the
hasattr(module_name, "attr_name")
function to find out if a module has a specific attribute.See the Python introspection for more information.
最简单的方法是使用
dir(objectname)
。 它将显示该对象的所有可用方法。The simplest method is to use
dir(objectname)
. It will display all the methods available for that object.我相信你想要这样的东西:
内置函数
dir()
可以完成这项工作。取自 Python shell 上的
help(dir)
输出:例如:
I believe that you want something like this:
The built-in function
dir()
can do this job.Taken from
help(dir)
output on your Python shell:For example:
对于许多对象,您可以使用此代码,将“object”替换为您感兴趣的对象:
我在 diveintopython.net (现已存档),应该提供一些进一步的详细信息!
如果您收到
AttributeError
,您可以使用它:getattr()
不能容忍 pandas 风格的 Python 3.6 抽象虚拟子类。 此代码的作用与上面相同,并且忽略异常。For many objects, you can use this code, replacing 'object' with the object you're interested in:
I discovered it at diveintopython.net (now archived), that should provide some further details!
If you get an
AttributeError
, you can use this instead:getattr()
is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.