繁体   English   中英

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

[英]Mutating / in-place function invokation or adaptation in Python

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

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

这是非常清楚的,但同时又冗长且多余。 有没有什么方法可以通过使some_function充当“变异”(“就地”)函数来简化这个语句?

例如,在Julia 中,通常可以执行以下操作:

some_function!(long_descriptive_variable_name)

并将其分派到some_function的版本,该版本直接写入long_descriptive_variable_name ,从而有效地更新变量。

有没有办法在Python中简洁地表达相同的泛型函数some_function

用一般对象方法做同样的事情呢? 即简化

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的Zen:

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没有++ / -- x += 1达到同样的效果时,添加它会有更多的工作。 这里也是如此,在调用函数时,几个人需要花费大量的工作来节省一些关键的笔触。

免责声明:这不应该用于任何严肃的代码,我写它只是为了好玩,甚至不认为它是聪明的。

不确定这是否是你想要的(如果它不是主题的话,请原谅我),但我在创造这个时真的很开心。

class FancyThing(object):

    def __init__(self, value):

        self.value = value

    def update(self, callback):

        self.value = callback(self.value)

    def __get__(self, instance, owner):

        return instance.value

    def __set__(self, instance, value):

        instance.value = value

    def __str__(self):

        return str(self.value)

    def __add__(self, other):

        return self.value + other

如果您在此类中包装某些内容,则可以使用任何随机回调进行update

def some_func(val):
    return val * 3

a = FancyThing(3.5)
print a

a.update(tester)
print a
b = a + 5
print b

输出:

3.5
10.5
15.5

有趣的是,您必须定义许多内置方法才能像普通方法一样使用内部值,就像我为__add__()所做的__add__()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM