gpt4 book ai didi

python - Python中有一个函数可以列出特定对象的属性和方法吗?

转载 作者:IT老高 更新时间:2023-10-28 21:37:07 26 4
gpt4 key购买 nike

Python 中有没有列出特定对象的属性和方法的函数?

类似:

ShowAttributes ( myObject )

-> .count
-> .size

ShowMethods ( myObject )

-> len
-> parse

最佳答案

你想看看dir()功能:

>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.


根据评论进行编辑:

不,这也会显示所有继承的方法。考虑这个例子:

test.py:

class Foo:
def foo(): pass

class Bar(Foo):
def bar(): pass

Python 解释器:

>>> from test import Foo, Bar
>>> dir(Foo)
['__doc__', '__module__', 'foo']
>>> dir(Bar)
['__doc__', '__module__', 'bar', 'foo']

您应该注意 Python's documentation状态:

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

因此,在您的代码中使用它是不安全的。请改用 vars()Vars() 不包含有关父类(super class)的信息,您必须自己收集它们。


如果您使用 dir() 在交互式解释器中查找信息,请考虑使用 help()

关于python - Python中有一个函数可以列出特定对象的属性和方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com