2013-05-01 83 views
0

我試圖瞭解使用dir函數時的幾種方法。Python中的Dir函數

例如,當我執行以下命令時,它列出了以下方法。與__開頭的方法是int對象內建的方法,但我怎麼使用其他功能,如bit_lengthconjugate,在real情況下,我用它作爲i.realbit_lenghth我用它作爲i.bit_length()

如何識別時作爲屬性使用(真正的),當爲方法調用(bit_length())使用方法:

>>> i=0 
>>> 
>>> dir(i) 
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delat 
tr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__forma 
t__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', 
'__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul 
__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow 
__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ 
ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ro 
r__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rx 
or__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '_ 
_truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', ' 
imag', 'numerator', 'real'] 
+0

通常通過讀取文件;在任何情況下調用可能是方法的東西而不知道它應該做什麼聽起來都是個壞主意。 'help(i.bit_length)'或'help(i)'。 – geoffspear 2013-05-01 14:18:02

回答

1

您可以檢查是否something是使用hasattr

hasattr(something, '__call__') 
功能
0

方法有__call__屬性,所以爲了確定是否可以調用某些東西,請使用:

hasattr(val, '__call__') 

問題是方法可以有參數,所以你必須檢查參數列表(例如,使用類似Python list function argument names SO的問題)

5

方法屬性。它們只是可調用的屬性。

您可以測試,如果事情是可調用的使用內置callable() function

>>> 1 .bit_length 
<built-in method bit_length of int object at 0x7fe7b2c13118> 
>>> callable(1 .bit_length) 
True 
>>> callable(1 .real) 
False 
+0

我想你可能想提到類也可以調用,但調用類會導致構建類的實例。 :) – J0HN 2013-05-01 14:03:45

+0

+1,我不知道['callable()'](http://docs.python.org/2/library/functions.html#callable)。 Docs:*「如果類實例具有__call __()方法,則可以調用它們。」* – 2013-05-01 14:03:45

+1

@ J0HN:'int'也可以調用,所有'工廠'也一樣。元類是可調用的,它們產生新的類等等。調用它們時產生返回一個新對象,但許多函數也是如此。 :-) – 2013-05-01 14:07:14