具有另一个函数作为可选参数的函数

问题描述 投票:1回答:3

我正在尝试编写一个将另一个函数作为可选参数的函数。我对语法有些困惑(并感到困惑)。我希望func2是一个可选参数。因此,我只希望在func1中调用它时才能工作。我希望它在我具有更复杂的文件模式时用作过滤器功能。 glob.glob(files + '/*')可以提供指定目录中的所有文件。 (glob.glob(path + '/' + file_name + '*'))可以给出更复杂的模式,但我不确定如何将其实现为可选函数参数。任何帮助将非常感激!

import glob

def func1(dirs, func2):

    if type(dirs) == list:
        for files in dirs:
            files = glob.glob(files + '/*')
            print(files) # prints all of the file names in each directory given
            if func2:
                func2(file_name)          



def func2(file_name):
    if file_name in files:
        print(file_name)
        # (glob.glob(path + '/' + file_name + '*'))

func1(['C:\path\to\files1\', 'C:\path\to\files2\'], func2('test2'))

对于此示例,假设\ files1包含'test1.txt'和'test2.txt',而files2包含'test1.jpg'和'test2.jpg'。我要func1打印test2.txt和test1.jpg的路径。

python python-2.x glob
3个回答
1
投票

唯一的区别是您如何传递函数。您当前正在传递returnfunc2('test2'),您应该仅传递func2。还请确保将files传递给func2,否则将无法定义。

import glob

def func1(dirs, func2):

    if type(dirs) == list:
        for files in dirs:
            files = glob.glob(files + '/*')
            print(files) # prints all of the file names in each directory given
            if func2:
                func2(file_name, files)          



def func2(file_name, files):
    if file_name in files:
        print(file_name)
        # (glob.glob(path + '/' + file_name + '*'))

func1(['C:\path\to\files1\', 'C:\path\to\files2\'], func2)

1
投票

在您的第一个函数中,使用具有不同名称的可选参数类型。

这足以完成您的代码。

import glob

def func1(dirs, printer=False):

    if type(dirs) == list:
        for files in dirs:
            files = glob.glob(files + '/*')
            print(files) # prints all of the file names in each directory given
            if printer is True:
                func2(file_name)          



def func2(file_name):
    if file_name in files:
        print(file_name)
        # (glob.glob(path + '/' + file_name + '*'))

# EXECUTE WITHOUT FUNCTION CALLING FUNC2
func1(['C:\\path\\to\\files1\\', 'C:\\path\\to\\files2\\'])

# EXECUTE WITH FUNCTION CALLING FUNC2
func1(['C:\\path\\to\\files1\\', 'C:\\path\\to\\files2\\'],True)


0
投票

或者,您可以通过将参数作为lambda传递来延迟对func2的调用>

func1(['C:\\path\\to\\files1\\', 'C:\\path\\to\\files2\\'], lambda _ : func2('test2')) 
© www.soinside.com 2019 - 2024. All rights reserved.