0

在 Python 中获取内置函数的字符串版本的最佳方法是什么?

IE

>>> import operator
>>> gt = operator.gt
>>> gt
<function _operator.gt>
>>> str(gt)
'<built-in function gt>'

>从哪里回来最好的方法是什么gt?(注意:我实际上只需要这些运算符:>、、、、<和)。>=<===!=

4

2 回答 2

3

您可以访问内置函数的doc属性,其中包含描述该函数的有用注释。

>>> operator.lt.__doc__
'lt(a, b) -- Same as a<b.'
>>> operator.gt.__doc__
'gt(a, b) -- Same as a>b.'
>>> operator.eq.__doc__
'eq(a, b) -- Same as a==b.'
>>> operator.ne.__doc__
'ne(a, b) -- Same as a!=b.'
于 2019-09-12T17:54:56.067 回答
1

在@Milton 给出的答案之上,我们可以做到:

import re, operator

def get_symbol(op):
    sym = re.sub(r'.*\w\s?(\S+)\s?\w.*','\\1',getattr(operator,op).__doc__)
    if re.match('^\\W+$',sym):return sym

例子:

 get_symbol('matmul')
'@'
get_symbol('add')
 '+'
get_symbol('eq')
'=='
get_symbol('le')
'<='
get_symbol('mod')
'%'
get_symbol('inv')
'~'
get_symbol('ne')
'!='

仅举几例。你也可以这样做:

{get_symbol(i):i for i in operator.__all__} 

这为您提供了带有符号的字典。你会看到abs给出的东西不正确,因为没有实现符号版本

于 2019-09-12T18:44:22.827 回答