3

複数のアイテムを返すメソッドがあります。

def multiReturn():
   return 1,2,3,4

そしてそれを1行に割り当てています

one, two, three, four = multiReturn()

上記の行をクリーンアップする方法はありますか

何かのようなもの:

one,
two,
three,
four = multiReturn()

大きくなった変数名がいくつかあり、ページの幅が気になるからです。

それをきれいにするための任意のアイデア

4

4 に答える 4

10

括弧を使用できます。

(
    one,
    two,
    three,
    four
) = range(4)
于 2013-07-24T21:06:43.273 に答える
8

すでに非常に多くのアイテムを返している場合は、何らかのデータ構造を作成することを検討してください。クラスは問題ないはずですが、やり過ぎだと考える場合は、 dict またはnamedtupleを使用することもできます。

# First define the structure
myStruct = namedtuple('myStruct', ['item1', 'item2', 'item3', 'item4'])

# Then use it
def multiReturn():
    return myStruct(1,2,3,4)

# No unpacking required!
this_is_awesome = multiReturn()
于 2013-07-24T21:07:25.220 に答える
2

各行の終わりにバックスラッシュを使用します。

one, \
two, \
three, \
four = multiReturn()
于 2013-07-24T21:06:14.067 に答える
-1

Shorten your variable names.

No, really. If you can't fit usual width constraints, it 's a hint that you need some refactoring. Let me get to that.

To remain clear, names should be kept short. On the other hand, you need them to describe the value they are holding, or code they are performing (i case of functions etc.)

If it's hard for you to describe the value and keep the name short, it means that for any person reading your code it will be most probably even much harder to read and understand, since you make them concentrate on multiple things.

For comaprison, if I am to write something like:

class App():

    def __init__(self):

        self.config = {}
        self.error = ""
        # ...
        configDatabaseConnection = mydbmodule.conect(credentials)
        configQuery = "this and that"
        config = configDatabaseConnection.query(configQuery)
        configDatabaseConnectionErrorString = (configDatabaseConection.error)
        if configDatabaseConnectionErrorString:
            raise configError(configDatabaseConnectionErrorString)
        # ...

it normally means that I need to separate the configutation to another method, and use that instead:

class App():

    def __init__(self, credentials):

        self.config = self.load_config(credentials)
        self.error = ""
        # ...

        self.load_config()

     def load_config(self, credentials):

        conn = mydbmodule.conect(credentials)
        q = "this and that"
        config = conn.query(q)
        if conn.error:
            raise configError(conn.error)
        self.config = config

which is much more readable, and allows adding more logic to configuration procedure (say, fall-backs, reading from file instead of db...) without cluttering the gist of my code.

于 2013-07-24T21:09:17.470 に答える