6

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

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

这很清楚,但同时又冗长且有些多余。Python中是否有任何方法可以通过将 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 考虑在不久的将来进行此更改?

4

2 回答 2

1

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

>>> 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 没有++/ 。当实现同样的事情时,添加它会做更多的工作。这里也是如此,在调用函数时需要几个人的大量工作才能为您节省一些击键。--x += 1

于 2015-07-08T15:11:15.750 回答
0

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

不确定这是否是你想要的(如果离题,请原谅我),但我在创作时真的很享受。

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__().

于 2015-07-08T15:25:12.860 回答