secretbase.log

.NET/C#/Pythonなど

Python の型の安全性

Python には変数の型宣言が必要なく、動的な型付けをします。では異なる型同士を演算するとどうなるのでしょう?

動的な型付け

下記の例では、変数 x, y はそれぞれ事前に型を定義することなく、代入することができます。

$ python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> x=5
>>> y="37"
>>>
>>> x
5
>>>
>>> y
'37'
>>>

組み込み関数 type を使って、それぞれの変数の型を見ることができます。

>>> type(x)
<type 'int'>
>>>
>>> type(y)
<type 'str'>
>>>

Python の異なる型同士の演算

では、intである x と str である y を足し算するとどうなるでしょう?

>>> z=x+y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

TypeError となり、int 型 と str型は加算できないようになっていて、安全です。

型変換をして演算してみる

型を変換することができます。

文字として結合する場合

>>> a=str(x)+y
>>>
>>> a
'537'

整数型として加算する場合

>>> b=x+int(y)
>>>
>>> b
42

Python において、異なる型同士を演算するとエラーが発生することがわかりました。また、 str() や int() を用いて型変換することで演算もできます。