python - 如何通过传递 **args 来更新函数变量

标签 python python-3.x

目前我正在尝试将 Python 的“类功能”放入函数中。

示例代码:

def image_gen(**kwargs):
    anglerange= 45
    print(image_gen.__dict__)
    image_gen.__dict__.update(kwargs)
    print(image_gen.__dict__)
    print(anglerange)

args = dict(anglerange=15)

image_gen(**args)

返回:

{}
{'anglerange': 15}
45

这不是解决参数更新的正确方法,但是正确的方法是什么?在类中你可以调用 self.update.__dict__ ,它是如何在函数中配置的?

我需要函数中的参数初始化才能运行标准副本。

使用Python 3.5

最佳答案

我可能会误解这一点,但我认为您将遇到的问题是函数数据将跨越“实例”,因为该函数只有一个副本,并且该函数的所有使用都将共享同一个对象。请参阅以下示例:

# helper function, not really relevant
def print_non_builtins(func):
    orig = dir(func) + ['inspect']
    func.inspect = lambda: {k: getattr(func, k) for k in dir(func) if k not in orig}
    return func

@print_non_builtins
def function_with_data(**kwargs):
    for k, v in kwargs.items():
        setattr(function_with_data, k, v)


function_with_data(a=1, b=2)
print(function_with_data.inspect())
# {'a': 1, 'b': 2}

function_with_data(b=3)
print(function_with_data.inspect())
# {'a': 1, 'b': 3}

关于python - 如何通过传递 **args 来更新函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541175/

相关文章:

python - 未为 django.db.models 字段默认定义可调用

python - 使用python在OpenCV中使用已知的特定添加点添加两个图像

python-3.x - 如何使用多个列值对 pandas 数据框进行数据透视表/数据透视表

python - 使用正则表达式混合字符串

python - Pandas DataFrame 乘以列并创建新列

Python3.6 优于 Python 3.4

python - 影响其他对象列表的对象列表

python - 共享/备份时使用 .py 或 .pyc 文件?

python - 使用 Python 如何从 Excel 文件获取输入、定义函数并在该 Excel 文件的新工作表中生成输出?

google-app-engine - 适用于 Google App Engine 的 Python 3