「Pythonの引数の引き渡し」の版間の差分
提供: tknotebook
(ページの作成:「Category:コンピュータCategory:Python メインページ>コンピュータの部屋#Python>Python Tips pythonは大変わかりやすい...」) |
|||
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は大変わかりやすい言語ですが、ひとつわかりにくい基本的な事項があります。
関数への引数の引き渡し方です。
引数の引き渡し方といえば
- 値渡し(Call By Value)
- 参照渡し(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