首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为函数参数(Python)指定类型

如何为函数参数(Python)指定类型
EN

Stack Overflow用户
提问于 2022-10-07 18:02:42
回答 3查看 538关注 0票数 1

我想限制可以作为参数传递给另一个函数的函数范围。例如,将函数限制为两个指定的函数中的一个,或者来自特定模块,或者通过签名。我尝试了下面的代码,但是现在有一些限制: as参数可以被传递给任何函数。

这在Python中是可能的吗?

代码语言:javascript
运行
复制
def func_as_param():
    print("func_as_param called")


def other_func():
    print("other_func called")


def func_with_func_arg(func: func_as_param):  # this is not giving restrictions
# def func_with_func_arg(func: type(func_as_param)):  # this is also not giving restrictions
    print("func_with_func_arg called")
    func()


def test_func_with_func_arg():
    print("test_func_with_func_arg")
    func_with_func_arg(func_as_param)
    func_with_func_arg(other_func)  # <- here IDE must complain that only func_as_param is expected
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-10-07 18:29:50

期望特定签名的回调函数的

框架可能会使用Callable[[Arg1Type, Arg2Type], ReturnType]暗示类型。

您可能需要使用可调用类型。这可能对https://docs.python.org/3/library/typing.html#callable有帮助

注意事项

Python中的类型注释与C中的类型注释不同,它们是可选的语法块,我们可以添加这些代码以使代码更加明确。错误的类型注释只会在我们的代码编辑器中突出显示不正确的注释--不会因为注释而引发错误。如果有必要的话,你必须自己做检查。

票数 3
EN

Stack Overflow用户

发布于 2022-10-07 18:29:28

通常这是通过创建您自己的类型(类)来完成的。然后,任何其他函数都可以从它继承,并将是相同的“类型”。

代码语言:javascript
运行
复制
class my_functions:
    pass

class func_as_param_class(my_functions):

    @staticmethod
    def __call__():
        print("func_as_param called")

func_as_param = func_as_param_class() # create the callable function ....


def other_func():
    print("other_func called")


def func_with_func_arg(func: my_functions): # only my_functions are accepted.
# def func_with_func_arg(func: type(func_as_param)):
    print("func_with_func_arg called")
    func()


def test_func_with_func_arg():
    print("test_func_with_func_arg")
    func_with_func_arg(func_as_param)
    func_with_func_arg(other_func)  # <- here IDE must complain that only func_as_param is expected

在上面的代码中,我的IDE (py魅力)确实抱怨other_func是错误的类型,但是这并不在运行时执行任何限制,它只允许IDE linter和mypy发出违规警告。

编辑:通过将调用函数声明为静态来删除参数。

票数 2
EN

Stack Overflow用户

发布于 2022-10-07 18:09:12

我不知道Python不对类型注释做任何更改是不是只有我一个人

语法:

代码语言:javascript
运行
复制
def greeting(name: str) -> str:
    return 'Hello ' + name

您可以在这里找到更多信息:https://docs.python.org/3/library/typing.html

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73991045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档