2014年2月6日木曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART II.(Types and Operations)、CHAPTER 4(Introducing Python Object Types)、Test Your Knowledge: Quiz 3を解いてみる。

その他参考書籍

Test Your Knowledge: Quiz 3

不変性を持つオブジェクトのこと。

不変性を持つオブジェクトは、文字列、数値、タプル等。

逆に変更可能なのはリスト、bytearray等。

不変性を持つオブジェクトを変更したようにしたい場合は、新しいオブジェクトを作成することになる。

入出力結果(Terminal)

$ python3
Python 3.3.3 (default, Dec  2 2013, 01:40:21) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "python"
>>> n = 10
>>> t=(1,2)
>>> l = [1,2]
>>> b=bytearray(b'python')
>>> s[0] = 'a' # エラー
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> t[0] = 10 # エラー
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> l[0] = 10 # リストは変更可能
>>> l
[10, 2]
>>> b.extend(b' programmer')
>>> b
bytearray(b'python programmer')
>>> s + ' programmer' # 変更されない
'python programmer'
>>> s
'python'
>>> s = 'a' + s[1:] # 新規に作成
>>> s
'aython'
>>> t = (10,) + t[1:] # 新規に作成
>>> t
(10, 2)
>>> quit()
$

0 コメント:

コメントを投稿