6

コードには、次のことを行うステートメントがよくあります。

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

これは非常に明確ですが、同時に冗長で冗長です。some_functionおそらく「変更」(「インプレース」)関数として機能させることにより、このステートメントを単純化する方法はPythonにあり ますか?

たとえば、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に関しては、承認されるとは思えません。値を暗黙的に変更する次のような関数を呼び出すことは、Zen of 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 に答える