Python将参数作为参数的方法传递给另一个指定defau的方法

2024-04-20 05:00:26 发布

您现在位置:Python中文网/ 问答频道 /正文

表达式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


Tags: txtreturndefextensionrepochangelogoutoutfile
2条回答

作为对DrV答案的补充:

在Python中,函数的签名是在解释器第一次看到时计算的,而不是在调用时。因此,就范围而言,您的代码相当于以下代码:

b = a
a = 1

输出:

b = a
NameError: name 'a' is not defined

我希望你现在明白了,为什么你的代码不起作用。你知道吗

另一方面:虽然这种行为使得对默认参数表达式求值的范围更加明显,但它也很容易产生错误,例如:

def foo(bar = []):
    bar.append(1)
    return bar

print(foo())
print(foo())

输出:

[1]
[1, 1]

在这里,默认值总是相同的列表-在foo的所有调用中-因为函数签名只计算一次。解决方案是使用None作为默认值并执行显式检查:

def foo(bar = None):
    if bar is None:
        bar = []
    bar.append(1)
    return bar

print(foo())
print(foo())

输出:

[1]
[1]

这是秩序问题。由于_changelog_txt在定义函数`writeChangelog时尚未定义,因此它会抛出一个错误。你知道吗

这样做有效:

def b(s):
    print s

def a(f=b):
    f("hello")

a()

这并不意味着:

def a(f=b):
    f("hello")

def b(s):
    print s

a()

应该注意的是,这与关键字参数default值是函数无关。它可以是在定义函数之前未定义的任何其他对象。当解释器遇到_changelog_txt时,不存在这样的情况。你知道吗

在这种情况下,重新排序代码是一个很好的选择。你知道吗

运行时的情况是不同的,因为在运行任何东西之前,解释器已经遇到了所有的def问题。这就是为什么在python中很少碰到这种问题的原因。你知道吗

相关问题 更多 >