LoginSignup
5
9

More than 3 years have passed since last update.

【Python】蛇使いへの道 (3) Pythonのクラス

Last updated at Posted at 2016-11-20

Pythonを使ったデータサイエンティストになるための修行です。
型を制するものは全てを制すということでPythonの主要なクラスをやります。

PREV【Python】蛇使いへの道 (2) Pythonの基本
NEXT【Python】蛇使いへの道 (4) Numpyを手なずける

Pythonの主要なクラス

クラス 説明 分類 インスタンス例
object object型 オブジェクト object()
bool 論理型 論理値 True, False
int 整数型 数値 26, 0b11010, 0o32, 0x1a
float 浮動小数点型 数値 3.1415, 1.5e-3, 1/2
complex 複素数型 数値 1j, 1.1+2.3j
tuple タプル型 シーケンス (), (1,), (True,False)
list リスト型 シーケンス [],[1], [True,False]
str 文字列型 シーケンス 'man',"man",'人',"人"
bytes バイト列型 シーケンス b'man', b'¥xe4¥xba¥xba'
bytearray バイト配列型 シーケンス bytearray(b'man')
range 範囲型 イテレータ range(1,10,2)
dict 辞書型 マッピング {}, {'y':2014,'m':12,'d':25}
set 集合型 集合 {1,3,5,7,9}
function 関数型 関数 lambda x:x**2

クラスの調べ方

type()を使う。

In [1]: type('man')
Out[1]: str

または、isinstance()を使う。

In [2]: isinstance('man', str)
Out[2]: True

In [3]: isinstance('man', bytes)
Out[3]: False

isinstance(x, X)type(x)Xのサブクラスである場合でもTrueとなります。
つまり、すべてのクラスはオブジェクトクラスのサブクラスということです。

In [4]: isinstance('man', object)
Out[4]: True

In [5]: issubclass(str, object)
Out[5]: True

クラス変換(cast)

大体は変換先クラスの第1引数に変換元を入れれば変換できる。

In [6]: float(1) #int to float
Out[6]: 1.0

In [7]: int(-1.9) #float to int
Out[7]: -1

In [8]: complex(0) #int to complex
Out[8]: 0j

In [9]: list((1, 2, 3)) #tuple to list
Out[9]: [1, 2, 3]

In [10]: tuple([1, 2, 3]) #list to tuple
Out[10]: (1, 2, 3)

In [11]: list(range(5)) #range to list
Out[11]: [0, 1, 2, 3, 4]

In [12]: list('abc') #str to list
Out[12]: ['a', 'b', 'c']

bool

boolクラス(論理型)の真、偽はTrue,Falseで表現されます。
否定、論理積、論理和に対する演算子はnot, and, orです。

In [13]: not True, True and True, True or False
Out[13]: (False, True, True) 

全てのobjectがboolにcast可能です。
Pythonでは条件文など、さまざまな状況で暗黙の論理型への変換が行われます。

In [14]: bool(0), bool(0.1), bool(()), bool([]), bool({}), bool({0})
Out[14]: (False, True, False, False, True)

整数の論理積と論理和では評価手続きにおける最後の整数が戻されます。
In [16]は整数のbitごとの論理積、論理和です。

In [15]: 3 and 6, 3 or 6, 1 and 0 
Out[15]: (6, 3, 0)

In [16]: 3 & 6, 3 | 6
Out[16]: (2, 7)

int, float

int型に上限はありません。

In [26]: 10 ** 30
Out[26]: 1000000000000000000000000000000

10 / 5float, 10 // 5intになります。

In [27]: 10 / 5, 10 // 5
Out[27]: (2.0, 2)

商と余りを求める。

In [28]: 10 // 3, 10 % 3 
Out[28]: (3, 1)

list, tuple

  • listは要素、部分列の変更が可能
  • tupleは変更ができない

list

listの生成

In [29]: a = [10, 20, 30, 40, 50]

インデックスで参照できます。
-1でリストの最後を参照できます。

In [30]: a[0], a[-1]
Out[30]: (10, 50)

もちろん変更もできます。

In [31]: a[0], a[-1] = 11,51

シーケンスに対してはスライスという機能が使えます。

# 文字列オブジェクト[開始インデックス:終了インデックス]
In [32]: a[1:4]
Out[32]: [20, 30, 40]

スライスの3つ目の引数にはステップを指定できます。
これを使うと指定の数だけ飛ばして参照できます。

In [33]: a[::2]
Out[33]: [11, 30, 51]

tuple

tupleの生成

In [33]: a = (10,20,30,40,50)

tupleも同様にインデックスで参照できます。
誤解釈されない限り、tupleの()は省略できます。

In [34]: a[0], a[-1]
Out[34]: (10, 50)

変更はエラーとなります。

In [35]: a[0] = 11
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-1ffcdc5ca638> in <module>()
----> 1 a[0]=11

TypeError: 'tuple' object does not support item assignment

結合はできる。

In [36]: a, b = (1,2),(True,'Japan',(None,'dog'))

In [37]: a + b
Out[37]: (1, 2, True, 'Japan', (None, 'dog'))

追加はできない。

In [38]: a.append(10)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-52-fb2e87d24477> in <module>()
----> 1 a.append(10)

AttributeError: 'tuple' object has no attribute 'append'

tupleの存在意義

listに制限つけただけじゃんと思われるかもしれませんがtupleには以下の意味があります。

  • dict(辞書)のkeyになれる
  • mutableでない分、listより高速に処理ができる
  • tupleは元々、複数のobjectを「単純に」1個にまとめるという意味がある

str, bytes, bytearray

str(文字列)は常にUnicodeを意味します。
これに対して、bytes, bytearray は単純なbyte列です。
bytesbytearrayの違いは、tuplelistの違いと同じです。

文字列の参照方法は基本的にlistやtupleと同じです。

In [53]: a, b = 'ABCDE','FG'

In [54]: a[0],a[-1],a[-2],a[1:4]
Out[54]: ('A', 'E', 'D', 'BCD')

triple quoteで改行を含めることができます。


In [55]: s = '''
   ....: #include <stdio.h>
   ....: int main(){
   ....:   printf("hello world\n");
   ....:   return 0;
   ....: }
   ....: '''

In [56]: s
Out[56]: '\n #include <stdio.h>\n int main(){\n printf("hello world\n");\n return 0;\n}\n'

dict

listでは、indexは0から始まる整数でしたが、dict(辞書型)では、このindexに相当するkeyとして整数、文字列、tupleなどが使用できます。

In [61]: exts={'py':'Python','rb':'Ruby','pl':'Perl'}

In [62]: for key in exts:
   ....:     value=exts[key]
   ....:     print(key,value)
pl Perl
py Python
rb Ruby

items()を使えばkeyとvalueを一緒に取り出せます。

In [63]: for key,value in exts.items():
   ....:     print(key,value)
pl Perl
py Python
rb Ruby

keyがdictに含まれるかどうかはinを使用します。

In [64]:  'py' in exts, 'c' in exts
Out[64]: (True, False)

NEXT【Python】蛇使いへの道 (4) Numpyを手なずける

5
9
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9