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

2024-04-25 02:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

类似于:

ShowAttributes ( myObject )

   -> .count
   -> .size

ShowMethods ( myObject )

   -> len
   -> parse

Tags: 对象方法函数sizelen属性parsecount
3条回答

你想看看^{}函数:

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


根据评论进行编辑:

不,这也将显示所有继承的方法。举个例子:

测试.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()不包括有关超类的信息,您必须自己收集它们。


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

为了更便于阅读,您可以使用see

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

dir()和vars()不适合你吗?

相关问题 更多 >