在Python控制台中查看类方法

5

如果我在Python控制台中处理一个对象,有没有办法查看该类可用的方法?

4个回答

9
如果您所说的“class”实际上是您拥有的实例,您可以简单地使用dir:
a = list()
print dir(a)

如果你真的想查看你对象所属类的方法:

a = list()
print dir(a.__class__)

请注意,在这种情况下,两者将打印相同的结果,但是由于Python非常动态,您可以想象将新方法附加到实例上,而不会反映在类中。
如果您正在学习Python并希望在良好的环境中受益于其反射功能,我建议您看一下IPython。在IPython内部,您可以获得方法/属性的Tab补全。

谢谢。第一个案例是我想表达的,但了解两个案例也很好。 - Jason Swett

1

另一种让您查看对象文档字符串的方法是使用内置函数help()

>>> i = 1
>>> help(type(i))
Help on class int in module __builtin__:

class int(object)
 |  int(x[, base]) -> integer
 |  
 |  Convert a string or number to an integer, if possible.  A floating point
 |  argument will be truncated towards zero (this does not include a string
 |  representation of a floating point number!)  When converting a string, use
 |  the optional base.  It is an error to supply a base when converting a
 |  non-string.  If base is zero, the proper base is guessed based on the
 |  string content.  If the argument is outside the integer range a
 |  long object will be returned instead.
 |  
 |  Methods defined here:
 |  
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 | 

(...等等).


0

假设它的名称是"theobject": dir(theobject)


0
如果你想要使用制表符补全功能,可以使用Ipython,或者标准库中的rlcompleter
>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
readline.__file__         readline.insert_text(      readline.set_completer(
readline.__name__         readline.parse_and_bind(
>>> readline.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接