Is there a function in Python to list the attributes and methods of a particular object?
python中是否有列出特定对象的属性和方法的函数?
类似:
1 2 3 4 5 6 7 8 9 | ShowAttributes ( myObject ) -> .count -> .size ShowMethods ( myObject ) -> len -> parse |
您要查看
1 2 3 4 | >>> li = [] >>> dir(li) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] |
li is a list, sodir(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.
根据评论进行编辑:
不,这也将显示所有继承的方法。考虑这个例子:
测试:PY:
1 2 3 4 5 | class Foo: def foo(): pass class Bar(Foo): def bar(): pass |
python解释器:
1 2 3 4 5 | >>> from test import Foo, Bar >>> dir(Foo) ['__doc__', '__module__', 'foo'] >>> dir(Bar) ['__doc__', '__module__', 'bar', 'foo'] |
您应该注意,python的文档说明:
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.
因此,在代码中使用是不安全的。用
如果使用
dir()和vars()不适合您吗?
为了更具人类可读性,您可以使用see:
1 2 3 4 5 6 7 8 9 10 11 12 | In [1]: from see import see In [2]: x ="hello world!" In [3]: see(x) Out[3]: [] in + * % < <= == != > >= hash() help() len() repr() str() .capitalize() .center() .count() .decode() .encode() .endswith() .expandtabs() .find() .format() .index() .isalnum() .isalpha() .isdigit() .islower() .isspace() .istitle() .isupper() .join() .ljust() .lower() .lstrip() .partition() .replace() .rfind() .rindex() .rjust() .rpartition() .rsplit() .rstrip() .split() .splitlines() .startswith() .strip() .swapcase() .title() .translate() .upper() .zfill() |
另一种方法是使用漂亮的IPython环境。它允许您选项卡完成以查找对象的所有方法和字段。
令我惊讶的是,没有人提到python对象函数: