gpt4 book ai didi

python - Python 中的变异/就地函数调用或改编

转载 作者:太空狗 更新时间:2023-10-30 00:17:07 25 4
gpt4 key购买 nike

我的代码中经常有执行以下操作的语句:

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

这很清楚,但同时又冗长又有些多余。 Python 中是否有任何方法可以通过使 some_function 充当“变异”(“就地”)函数来简化此语句?

例如,在 Julia 中 one can often do以下内容:

some_function!(long_descriptive_variable_name)

这会被分派(dispatch)到直接写入 long_descriptive_variable_namesome_function 版本,有效地更新变量。

对于通用函数 some_function ,有没有什么方法可以在 Python 中简洁地表达相同的内容?

用通用的对象方法做同样的事情怎么样?即简化

long_variable_name = long_variable_name.method(arg1, arg2)

如果以上内容对于当前版本的 Python 来说不是(容易)可行的,那么在不久的将来是否有任何 PEP 考虑到这一变化?

最佳答案

你要求的可以这样实现,但我当然不建议这样做:

>>> x = 10
>>> def foo(func, string_of_var):
globals()[string_of_var] = func(globals()[string_of_var])

>>> def bar(x):
return x * 2

>>> foo(bar, 'x')
>>> x
20

就更改它的 PEP 而言,如果有的话,我怀疑它是否会获得批准。像这样调用隐式更改值的函数违背了 Python 的禅宗:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit. <==== Relevant line
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules. <==== also probably relevant
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea. <==== And this one for good measure
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

这也可能需要相当多的工作而不会给语言增加太多。 Python 没有用于 this reason++/-- .当 x += 1 实现同样的事情时,添加它会做更多的工作。这里也是如此,需要几个人的大量工作才能在调用函数时为您节省几次按键。

关于python - Python 中的变异/就地函数调用或改编,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31296033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com