Ame*_*ina 6 python in-place python-3.x mutating-function
我的代码中经常有语句执行以下操作:
long_descriptive_variable_name = some_function(long_descriptive_variable_name)
Run Code Online (Sandbox Code Playgroud)
这是非常清楚的,但同时又冗长且多余.有没有办法在Python中简化这个语句,或许可以将 some_functionact作为"变异"("就地")函数?
例如,在Julia 中,通常可以执行以下操作:
some_function!(long_descriptive_variable_name)
Run Code Online (Sandbox Code Playgroud)
并将其分派到some_function直接写入的版本long_descriptive_variable_name,有效地更新变量.
有没有办法在Python中为通用函数简洁地表达相同的内容some_function?
用一般对象方法做同样的事情呢?即简化
long_variable_name = long_variable_name.method(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
如果以上(当前版本的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
Run Code Online (Sandbox Code Playgroud)
至于更改它的政治公众人物(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!
Run Code Online (Sandbox Code Playgroud)
这也可能需要大量的工作,而不会增加太多的语言。由于这个原因, Python 没有++/ 。当达到同样的效果时,添加它会需要更多的工作。这里也是如此,在调用函数时,需要几个人进行大量的工作才能为您节省一些按键。--x += 1
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |