在python中使用两种不同类型的参数调用函数

时间:2013-05-14 14:58:20

标签: python python-2.7 ironpython

我是Python新手。我遇到了一个奇怪的案例,我无法弄清问题是什么。我有两个用Python编写的函数版本: -

v1 -

def fileLookUp(fixedPath, version):
    if version:
        targetFile="c:\\null\\patchedFile.txt"
    else:
        targetFile="c:\\null\\vulFile.txt"

#some more code follows

和v2 -

def fileLookUp(fixedPath, version):
    if version:
        print "ok"
    else:
        print "not ok"

#some more code follows

其中参数fixedPath是输入的字符串,参数version应该是整数值。第一个功能(v1)不能按预期工作,而第二个功能完美。该函数被称为fileLookUp("c:\\dir\\dir\\", 1)的两次。

在第一种情况下,收到的错误是: -

fileLookUp("D:\\Celine\\assetSERV\\", 1)
Exception: fileLookUp() takes exactly 2 arguments (1 given)

请让我知道为什么第一个函数抛出异常?

这是实际的代码......

from System.IO import *;

def fileLookUp(fixedPath, version):
if version:
    targetFile="c:\\null\\patchedFile.txt";
else:
    targetFile="c:\\null\\vulFile.txt";
vulFileHandle=open(targetFile,"a+");
temp=fixedPath;
if not Directory.GetDirectories(fixedPath):
    files=Directory.GetFiles(fixedPath);
    for eachFile in files:
        print eachFile;
        hash = Tools.MD5(eachFile);
        print hash;
        vulFileHandle.write(eachFile+'\t'+hash+'\n');
else:
    directory=Directory.GetDirectories(fixedPath);
    for folder in directory:
        if vulFileHandle.closed:
            vulFileHandle=open(targetFile,"a+");
        fixedPath="";
        fixedPath+=folder;
        fixedPath+="\\";
        vulFileHandle.close();
        fileLookUp(fixedPath);
    filess=Directory.GetFiles(temp);
    for eachFilee in filess:
        if vulFileHandle.closed:
            vulFileHandle=open(targetFile,"a+");
        print eachFilee;
        hashh = Tools.MD5(eachFilee);
        print hashh;
        vulFileHandle.write(eachFilee+'\t'+hashh+'\n');
if not vulFileHandle.closed:
    vulFileHandle.close();

它只是一个递归代码,用于打印目录中所有文件的哈希值。

3 个答案:

答案 0 :(得分:3)

你有一个电话“fileLookUp(fixedPath);”只有一个参数被发送到第26行左右(只是粗略计算)。你的定义不允许这样做。发送此调用中的版本,或在定义中为版本提供默认值。

答案 1 :(得分:1)

这些函数的编写方式,必须使用两个参数调用它们。您获得的错误消息表明仅使用一个参数调用其中一个消息。在Python中,如果要使参数可选,则必须显式声明可选参数在未提供时应具有的值。例如,由于versionint,并且您使用if version:对其进行测试,因此良好的默认值可能为0.您还可以使用None

def fileLookUp(fixedPath, version=0):
    # etc.

def fileLookUp(fixedPath, version=None):
    # etc.

如果0是有效的版本号,并且您想测试值是否实际传递,请使用第二个并专门针对None进行测试:

def fileLookUp(fixedPath, version=None):
    if version is None:
        # etc.

答案 2 :(得分:1)

在(格式错误的)完整示例中,您正在递归调用fileLookUp 而不是传递version参数。