LoginSignup
1
0

More than 5 years have passed since last update.

オブジェクトを関数にシェアしてしまった

Last updated at Posted at 2018-08-27

早速ですが、以下が問題再現のコードです、python version = 2.7.10

def test(miracle=[]):
    print 'mirale show up'

    miracle += [1]
    return miracle

target = [1, 2, 3]
other_thing = test(target)

print other_thing
test(other_thing)
print other_thing

アウトプット

miracle show up
[1, 2, 3, 1]
miracle show up
[1, 2, 3, 1, 1]

解説:testという奇跡を起こす関数があり、渡された変数に一個エレメントを追記します。

test関数を二回目呼び出す時、戻り値を受け取っていないにも関わらず、other_thingが変更されました

これはtestの関数がmutableなother_thingへの参照を持って、変更をして、スコープ外のオブジェクトに副作用を与えてしまったからです。

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0