2013年5月3日金曜日

開発環境

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

その他参考書籍

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

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

try:
    s = "string" + [1,2,3,4,5] 
    print(s)
except Exception as err:
    print(type(err), err, err.args)

try:
    l = [1,2,3,4,5] + (1,2,3,4,5)
    print(l)
except Exception as err:
    print(type(err), err, err.args)

try:
    d = {'a':1} + {'b':2}
except Exception as err:
    print(type(err), err, err.args)

# appendはリストに使える(文字列には使えない)
try:
    l = [1,2,3,4,5]
    l.append('a')
    print(l)
    s = "python"
    s.append("a")
    print(s)
except Exception as err:
    print(type(err), err, err.args)

# keysメソッドはディクショナリのメソッドであり、リストには使えない
try:
    print({'a':1}.keys())
    print(['a','b'].keys())
except Exception as err:
    print(type(err), err, err.args)

# リストや文字列に対してスライシングや連結の操作を行った場合、戻り値として得られる
# オブジェクトはそれぞれ元のオブジェクトの型と同じリストや文字列
l1 = [1,2,3,4,5]
l = l1[:]
s1 = "spam"
s = s1[:]
print(type(l), type(s))

l1 = [1,2]
l2 = ['a','b']
s1 = "spam"
s2 = "eggs"
l = l1 + l2
s = s1 + s2
print(type(l), type(s))

入出力結果(Terminal)

$ ./sample.py
<class 'TypeError'> Can't convert 'list' object to str implicitly ("Can't convert 'list' object to str implicitly",)
<class 'TypeError'> can only concatenate list (not "tuple") to list ('can only concatenate list (not "tuple") to list',)
<class 'TypeError'> unsupported operand type(s) for +: 'dict' and 'dict' ("unsupported operand type(s) for +: 'dict' and 'dict'",)
[1, 2, 3, 4, 5, 'a']
<class 'AttributeError'> 'str' object has no attribute 'append' ("'str' object has no attribute 'append'",)
dict_keys(['a'])
<class 'AttributeError'> 'list' object has no attribute 'keys' ("'list' object has no attribute 'keys'",)
<class 'list'> <class 'str'>
<class 'list'> <class 'str'>
$

0 コメント:

コメントを投稿