Python中的变异/就地函数调用或自适应

2024-05-23 10:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码中经常有这样的语句:

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

这是非常清楚的,但冗长和有点多余的同时。在Python中有没有什么方法可以简化这个语句,比如让some_function充当一个“mutating”(“in-place”)函数?你知道吗

例如,在Julia one can often do中:

some_function!(long_descriptive_variable_name)

它被分派到some_function版本,该版本直接写入long_descriptive_variable_name,有效地更新了变量。你知道吗

对于泛型函数some_function,是否有任何方法可以在Python中简洁地表达相同的内容?你知道吗

用一般的对象方法做同样的事情怎么样?i、 e.简化

long_variable_name = long_variable_name.method(arg1, arg2)

如果上述内容在当前版本的Python中不(容易)实现,那么在不久的将来是否有pep考虑进行此更改?你知道吗


Tags: 方法代码namein版本内容placefunction
2条回答

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

>>> 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

至于改变它的政治公众人物,如果有一个我怀疑它会得到批准。调用这样一个隐式更改值的函数违背了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达到同样的效果时,添加它可能需要更多的工作。在这里也是如此,在调用函数时,需要几个人做大量的工作来节省一些按键。你知道吗

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

不确定这是否是你想要的(所以请原谅我,如果这是离题),但我真的很享受自己创造这个。你知道吗

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__()所做的那样。你知道吗

相关问题 更多 >

    热门问题