【问题标题】:Automatically change variable coming into function to string自动将进入函数的变量更改为字符串
【发布时间】:2021-11-12 12:57:45
【问题描述】:

有没有办法在变量到达函数时自动改变它的类型,例如:

def my_func( str(x) ):
    return x

x = int(1)
type(x)

x = my_func(x)
type(x)

我知道这段代码行不通,但这只是为了解释我的问题。

我也知道我可以只做x = my_func(str(x)),但我特别想确保所有进入函数的变量都是字符串。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

解决问题的最简单方法是将输入显式转换为字符串,如下所示:

def my_func(x):
    x = str(x)
    # rest of your logic here
    return x

如果您不想明确地这样做,您可以(如 cmets 中的建议)使用装饰器:

from functools import wraps


def string_all_input(func):
    # the "func" is the function you are decorating

    @wraps(func) # this preserves the function name
    def _wrapper(*args, **kwargs):
        # convert all positional args to strings
        string_args = [str(arg) for arg in args]
        # convert all keyword args to strings
        string_kwargs = {k: str(v) for k,v in kwargs.items()}
        # pass the stringified args and kwargs to the original function
        return func(*string_args, **string_kwargs)

    return _wrapper

# apply the decorator to your function definition
@string_all_input
def my_func(x):
    # rest of your logic here
    return x

type(my_func(123))

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多