0

我在使用 dir 函数时试图了解一些方法..

例如,当我执行以下命令时,它列出了以下方法。任何以开头__的方法都是对象的内置方法int,但是我如何使用其他函数,例如bit_length, conjugate,以防real我将它用作i.real并且bit_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']
4

3 回答 3

5

方法也是属性。它们只是可调用的属性。

callable()您可以使用内置函数测试是否可以调用某些内容:

>>> 1 .bit_length
<built-in method bit_length of int object at 0x7fe7b2c13118>
>>> callable(1 .bit_length)
True
>>> callable(1 .real)
False
于 2013-05-01T14:01:22.153 回答
1

您可以检查是否something是使用的功能hasattr

hasattr(something, '__call__')
于 2013-05-01T13:59:46.383 回答
0

方法具有__call__属性,因此为了确定某些内容是否可调用,请使用:

hasattr(val, '__call__')

问题是方法可以有参数,所以你必须检查参数列表(例如使用类似Python list function argument names SO question)

于 2013-05-01T14:00:14.890 回答