我如何将特定参数设置为python的功能,就像c

发布于 2025-02-07 20:39:56 字数 97 浏览 1 评论 0原文

请如何指定所需的函数和参数类型的返回值,例如在C中,我们声明了这样的原型函数,然后键入它需要:

int *atoi(char *str)

please how can I specify the return values of a function and types of arguments it required , like in C we declare a prototype function like this and type it requires :

int *atoi(char *str)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我闹别瞎闹 2025-02-14 20:39:56

您可以将其用于参数和变量。但是问题在于,分配时可以随时更改此类型。

a:int = 4

但这也将在不增加错误的情况下起作用

a:int = "this is string"

,让我们获得函数参数

def func(arg1:int , arg2:str = "hello"): -> str
    #do something

以上函数将以第一个参数为第一个参数,将字符串作为第二个参数,并将输出字符串。

但是没有像C或Java这样的违约。这样的参数必须仅在指定的数据类型中。输出数据类型也是如此。

You can use this for both arguments and variables. But the problem is the this type can be changed at any time when assigning.

a:int = 4

but this also will work without raising error

a:int = "this is string"

and lets get function arguments

def func(arg1:int , arg2:str = "hello"): -> str
    #do something

The above function will take an integer as first argument , string as the second one and will output a string.

But there is no contrains like C or java. Such like arguments must be in the specified data type only. The same is for the output data type also.

沐歌 2025-02-14 20:39:56

不幸的是,在Python中,没有确定的约束方式。即,您可以编写这样的代码:

def func(a:int, b:str):
    print(type(a))
    print(type(b))

func("Hello!", 31)
# >>> <class 'str'>
# >>> <class 'int'>

如果要在代码上设置约束,我建议设置try/deve/exce 子句,该条款试图转换为正确的类型不起作用。像这样:

def func(a:int, b:str):
    try:
        a = int(a)
    except ValueError:
        raise ValueError(f"Input {a =} not understood as integer. ")

    try:
        b = str(b)
    except ValueError:
        raise ValueError(f"Input {b =} not understood as string. ")

# func("Hello!", 31) # raises value errors.
func(31, "Hello!") # passes. With variables cast to right type.

Unfortunately, in python there's no definitive ways of constraining. I.e. you can write code like this:

def func(a:int, b:str):
    print(type(a))
    print(type(b))

func("Hello!", 31)
# >>> <class 'str'>
# >>> <class 'int'>

If you want to set constraints on code, I would suggest setting up a try/except clause which tries to convert to the correct type, and raises an error if it does not work. Like so:

def func(a:int, b:str):
    try:
        a = int(a)
    except ValueError:
        raise ValueError(f"Input {a =} not understood as integer. ")

    try:
        b = str(b)
    except ValueError:
        raise ValueError(f"Input {b =} not understood as string. ")

# func("Hello!", 31) # raises value errors.
func(31, "Hello!") # passes. With variables cast to right type.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文