表达式logic=_changelog_txt
:
def writeChangelog(repo, milestone, overwrite=False, extension=u'.txt',
logic=_changelog_txt): # HERE
"""Write 'Changelog - <milestone>.txt'"""
outFile = _outFile(dir_=CHANGELOGS_DIR,
name=u'Changelog - ' + milestone.title + extension)
if os.path.isfile(outFile) and not overwrite: return outFile
issues = getClosedIssues(repo, milestone, skip_labels=SKIP_LABELS)
return logic(issues, milestone, outFile)
def writeChangelogBBcode(repo, milestone, overwrite=False):
"""Write 'Changelog - <milestone>.bbcode.txt'"""
return writeChangelog(repo, milestone, overwrite, extension=u'.bbcode.txt',
logic=_changelog_bbcode) # no errors here
def _changelog_txt(issues, milestone, outFile):
with open(outFile, 'w') as out:
out.write(h2(_title(milestone)))
out.write('\n'.join(ul(issues, closedIssue)))
out.write('\n')
return outFile
给了我Unresolved reference \_changelog\_txt
。做我想做的事,什么是最邪恶的方式?另见:What is the best way to pass a method (with parameters) to another method in python
作为对DrV答案的补充:
在Python中,函数的签名是在解释器第一次看到时计算的,而不是在调用时。因此,就范围而言,您的代码相当于以下代码:
输出:
我希望你现在明白了,为什么你的代码不起作用。你知道吗
另一方面:虽然这种行为使得对默认参数表达式求值的范围更加明显,但它也很容易产生错误,例如:
输出:
在这里,默认值总是相同的列表-在
foo
的所有调用中-因为函数签名只计算一次。解决方案是使用None
作为默认值并执行显式检查:输出:
这是秩序问题。由于
_changelog_txt
在定义函数`writeChangelog时尚未定义,因此它会抛出一个错误。你知道吗这样做有效:
这并不意味着:
应该注意的是,这与关键字参数default值是函数无关。它可以是在定义函数之前未定义的任何其他对象。当解释器遇到
_changelog_txt
时,不存在这样的情况。你知道吗在这种情况下,重新排序代码是一个很好的选择。你知道吗
运行时的情况是不同的,因为在运行任何东西之前,解释器已经遇到了所有的
def
问题。这就是为什么在python中很少碰到这种问题的原因。你知道吗相关问题 更多 >
编程相关推荐