简体   繁体   English

如何获得内置函数的字符串表示形式?

[英]How to get a string representation of a builtin function?

What is the best way to get a string version of a builtin function in Python? 在Python中获取内置函数的字符串版本的最佳方法是什么?

ie

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

What is the best way to get > back from gt ? gt返回>的最佳方法是什么? (Note: I only actually need this for these operators: > , < , >= , <= , == and != ). (注意:对于这些运算符,我实际上只需要它: ><>=<===!= )。

You could access the doc attribute of the built-in function which contains useful comments describing the function. 您可以访问内置函数的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.'

Building on top of the answer given by, @Milton we can do: 在@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

Examples: 例子:

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

Just to mention a few. 仅举几例。 You could also do: 您也可以这样做:

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

This gives you a dictionary with the symbols. 这为您提供了带有符号的字典。 You will see that somethings like abs gives gives incorrect since there is no symbolic version implemented 您将看到像abs这样的东西给出了错误的提示,因为没有实现符号版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM