Pythonの可変オブジェクトと可変オブジェクトについて

2022 ワード

周知のように、Pythonのすべてのオブジェクト(object)は、Pythonに内蔵されたtype()id()を使用して追跡することができる.一方、オブジェクトでは、可変および可変に基づいて可変オブジェクトと可変オブジェクトに分けることができます.
Pythonでは、一般的な可変タイプはlistdictであり、一般的な可変タイプは数字(int,float)、文字列(string)、tupleである.
可変タイプ
まず例を見てみましょう.
>>> a = 1
>>> id(a)
30702344L
>>> a = 2
>>> id(a)
 30702320L
>>> id(1)
30702344L
>>> id(a+1)
 30702320L
>>> id(a+1) == id(3)
True
>>> string1 = 'Hello, World! Welcome to see Python's World'
>>> string2 = 'Hello, World! Welcome to see Python's World'
>>> id(string1) == id(string2)
True

すべての値が3の数に対して、メモリ領域で同じ空間を指していることがわかります.変数値が変化すると、その指向する空間も変化します.これは可変ではありません.
なお、 (string)は可変タイプであるが、 は可変タイプではない.次の例を見てみましょう.
>>> char1 = 'a'
>>> string1 = 'Hello, Python!'
>>> id(string1) == id('Hello, Python!')
True
>>> id(char1) == id('a')
False

可変タイプ
まず例を見てみましょう.
>>> list1 = [1,2]
>>> id(list1)
39504200L
>>> list1.append(3)
[1,2,3]
>>> id(list1)
39504200L
listが変化すると、変数が指すメモリ領域は変化しないことがわかります.
Variable
>>> def test1(somearg = []):
···        somearg.append(7)
···        print somearg
>>> def test2(somearg = 0):
···        somearg += 1
```        print somearg
>>> for _ in range(3):
···        test1()
···        test2()
[7]
1
[7, 7]
1
[7, 7, 7]
1 

この例では、デフォルトパラメータsomearg = []の処理方法は明らかに私たちが望んでいるものではありません.実際には、実行するたびに新しい空のlistを用意していません.では、どうすればいいですか.
>>> def test1(somearg = None):
···        if not somearg:
···            somearg = []
```        somearg.append(7)
```        print somearg
>>> for _ in range(3):
···        test1()
[7]
[7]
[7]