2013年2月7日木曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のII部(ビルトインオブジェクト)のまとめ演習7.(オブジェクトの操作に関する質問)を解いてみる。

その他参考書籍

7.(オブジェクトの操作に関する質問)

入出力結果(Terminal)

$ python
Python 3.3.0 (default, Sep 29 2012, 08:16:08) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # 異なる方のオブジェクトを+演算子で連結しようとするとエラーになる
... "" + []
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: Can't convert 'list' object to str implicitly
>>> []+(0,)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
>>> #+演算子はディクショナリには使えない
... {}+{}
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> {}+1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'int'
>>> {} + []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'list'
>>> # appendメソッドはリストのメソッド
... [].append(10)
>>> {'a':1}.append
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
>>> # keysメソッドはディクショナリのメソッドでリストには使えない
... [].keys()
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'list' object has no attribute 'keys'
>>> {}.keys()
dict_keys([])
>>> # スライシングや連結の操作の戻り値として得られるオブジェクトは元の型と同じ
... [][:]
[]
>>> type([][:])
<class 'list'>
>>> type("python"[:])
<class 'str'>
>>> type([]+[])
<class 'list'>
>>> type("" + "")
<class 'str'>
>>> quit()
$

0 コメント:

コメントを投稿