「Pythonの引数の引き渡し」の版間の差分

提供: tknotebook
移動: 案内検索
 
28行: 28行:
 
と表示されて 値渡しは明らかです。
 
と表示されて 値渡しは明らかです。
  
 +
しかし
  
 +
def fun(a):
 +
  a.append(3)
 +
 +
b = [1, 2]
 +
 +
bun(b)
 +
 +
print(b)
 +
 +
は [1, 2, 3] を出力します。
  
 
int
 
int

2018年9月11日 (火) 04:27時点における版

メインページ>コンピュータの部屋#Python>Python Tips


pythonは大変わかりやすい言語ですが、ひとつわかりにくい基本的な事項があります。 関数への引数の引き渡し方です。

引数の引き渡し方といえば

  1. 値渡し(Call By Value)
  2. 参照渡し(Call By Reference)

の2種類が定番ですが、pythonでは見かけ上全く同じ書き方でこの2種類が入り混じります。

例えば

def fun(a):
  a = "foo"

b="bar"
fun(b)
print(b)

を実行すると

bar

と表示されて 値渡しは明らかです。

しかし

def fun(a):
  a.append(3)
b = [1, 2]
bun(b)
print(b)

は [1, 2, 3] を出力します。

int float str tuple bool range type(None)


その他にもこんなのがあります。

bytes complex frozenset slice type type(Ellipsis) type(NotImplemented) types.FunctionType *これは mutable, 後述します。 types.BuiltinFunctionType weakref.ref