如何在python函数中指定传递的参数必须是函数[重复]

Posted

技术标签:

【中文标题】如何在python函数中指定传递的参数必须是函数[重复]【英文标题】:How to specify in a python function that a passed argument must be a function [duplicate] 【发布时间】:2019-06-06 13:36:29 【问题描述】:

我创建了一个函数,它接受一个函数作为参数。

如果我想指定一个函数接受一个整数,这很容易:

def fun(myInt:int=0):
    return myInt

但是当它需要一个函数时,我不能这样做:

def fun(myFun:function=print):
    myFun('whatever')

我打印了整数和函数的 type() 并得到了 <class 'int'> <class 'function'>

这两者有什么区别,是一种简单的方法来做我想做的事吗?

顺便说一句。我已经用过google了,找不到任何东西

【问题讨论】:

您正在使用类型提示,正确的拼写应该是使用typing.Callable generic。 好的,非常感谢! (看起来我需要知道我要找的东西的名字) 【参考方案1】:

在 Python 3 中:

from typing import Callable

def fun(myFun:Callable=print):
    myFun('whatever')

fun()
fun(print)
fun(type)

【讨论】:

以上是关于如何在python函数中指定传递的参数必须是函数[重复]的主要内容,如果未能解决你的问题,请参考以下文章