gpt4 book ai didi

python - 如何在给定指针的情况下获取函数的名称和/或描述

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:55 27 4
gpt4 key购买 nike

我正在使用 Python 2.7。有没有办法将名称、描述和可能的其他元数据与函数相关联,这样我就不必使用外部字典来保存此类信息,如下面的代码所示:

def predicateA(v):
# some logic that eventually returns a True/False value
return True

def predicateB(v):
# some logic that eventually returns a True/False value
return False

predicateNames={}
predicateNames[predicateA]='name and description for predicateA'
predicateNames[predicateB]='name and description for predicateB'

predicates = [predicateA, predicateB]

def evalForAllPredicates(v):
for f in predicates:
result = f(v)
print "function %s returned: %s" % (predicateNames[f], result)

evalForAllPredicates(3)

最佳答案

您可以通过 __name____doc__ 属性访问函数的名称及其文档字符串。函数的文档字符串只是作为函数中第一条语句放置的字符串文字。约定是使用三重引号将文档字符串括起来,因为它们预计会跨越多行。

def predicateA(v):
"""
some logic that eventually returns a True/False value
"""
return True

print "Name:", predicateA.__name__
print "Doc:", predicateB.__doc__

要将任意元数据关联到一个函数,只需将您喜欢的任何属性分配给该函数,就好像它是一个普通对象一样,毕竟它就是一个普通对象。

def predicateB(v):
"""
some logic that eventually returns a True/False value
"""
return False

predicateA.alwaysReturnsFalse = False
predicateB.alwaysReturnsFalse = True

for pred in [predicateA, predicateB]:
print "Function:", pred.__name__
print "Documentation:", pred.__doc__
if pred.alwaysReturnsFalse:
print "(This function always returns false)"
Function: predicateADocumentation:    some logic that eventually returns a True/False valueFunction: predicateBDocumentation:    some logic that eventually returns a True/False value(This function always returns false)

关于python - 如何在给定指针的情况下获取函数的名称和/或描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14642572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com