Pythonの基本 ~チュートリアル~

目次


目的
Pythonとは
Python基本
コメントアウト
一行をコメントアウト
複数をまとめてコメントアウト
文字列の表示:print
四則演算
論理型(Boolean)
論理演算子:and, or
Boolean値の四則演算
比較演算子
文字列処理
Nullオブジェクト:None
変数定義
リスト型
定義
要素を追加
要素を除外
スライス操作
インデックスの確認
結合
ある要素が含まれているか確認
長さ
タプル型
定義
長さ
結合
スライス操作
ある要素が含まれているか確認
辞書型
定義
アクセス
キーの確認
ある要素が含まれているか確認
要素を追加
要素を削除
set型
定義
要素を追加
重複する要素の確認
四則演算
ある要素が含まれているか確認
条件処理:If文
反復処理:For文
反復処理:While文
例外処理
With文
書き込み
読み込み
イテレータ(Iterator)
関数
基本的な使い方
可変長引数:args, kwargs
無名関数:lambda
関数の繰り返し利用:map
条件抽出
内包表記
モジュール(Module)
クラス(Class)
定義
継承
複数の継承


目的

  • Pythonの基礎知識をおさえる

Pythonとは

Pythonは、1991年にオランダ人のグイド・ヴァンロッサムというプログラマーによって開発され、現在オープンソースで運営されているプログラミング言語である。Pythonという名前の由来は、イギリスBBCのコメディ番組『空飛ぶモンティ・パイソン』だそう。

Pythonの用途は様々で多岐にわたる。

  • 組み込み開発
  • Webアプリケーション
  • デスクトップアプリケーション
  • 人工知能開発
  • ビッグデータ解析など

Pythonは、従来のプログラミング言語よりも、短く簡素なコードでプログラムを書けること特徴で、可読性も高い。また、専門的なライブラリが豊富にあるため、こうした既存のライブラリを有効に活用することで、自身の作りたいプログラムを簡単に作ることができるのもPythonの特徴である。

Python基本

これより先は、実際にPythonの使い方について解説していく。

参考サイト:https://learnxinyminutes.com/docs/python/

コメントアウト

一行をコメントアウト

# Comment out

複数をまとめてコメントアウト

""" Multiline strings can be written 
    using three "s, and are often used 
    as documentation.
"""

文字列の表示:print

# 「Hello, world!」という文字列を表示
print('Hello, world!')

Hello, world!

四則演算

# 足し算
print(1 + 1)   # => 2
print(8 - 1)   # => 7
print(10  2)  # => 20
print(35 / 5)  # => 7.0

2
7
20
7.0

# 割り算
print(5 // 3)       # => 1
print(-5 // 3)      # => -2
print(5.0 // 3.0)   # => 1.0
print(-5.0 // 3.0)  # => -2.0
print(10.0 / 3)  # => 3.3333333333333335

1
-2
1.0
-2.0
3.3333333333333335

# 剰余
print(7 % 3)   # => 1

1

# 累乗
print(23)  # => 8

8

# 組み合わせてみる
print(1 + 3  2)    # => 7
print((1 + 3)  2)  # => 8

7
8

論理型(Boolean)

# Boolean値は、次の2種類
print(True)
print(False)

True
False

# notで否定
print(not True)   # => False
print(not False)  # => True

False
True

論理演算子:and, or

print(True and False)  # => False
print(False or True)   # => True

False
True

Boolean値の四則演算

print(True + True) # => 2
print(True  8)    # => 8
print(False - 5)   # => -5

2
8
-5

比較演算子

# Boolean値と数値の比較
print(0 == False)  # => True
print(1 == True)   # => True
print(2 == True)   # => False
print(-5 != False) # => True

True
True
False
True

# 等しい
print(1 == 1)  # => True
print(2 == 1)  # => False

True
False

# 等しくない
print(1 != 1)  # => False
print(2 != 1)  # => True

False
True

# 大小関係
print(1 < 10)  # => True
print(1 > 10)  # => False
print(2 <= 2)  # => True
print(2 >= 2)  # => True

True
False
True
True

# 演算子の組み合わせ
print(1 < 2 and 2 < 3)  # => True
print(2 < 3 and 3 < 2)  # => False

# 以下でもOK
print(1 < 2 < 3)  # => True
print(2 < 3 < 2)  # => False

True
False
True
False

# isの役割
a = [1, 2, 3, 4]  # リスト型を作成, [1, 2, 3, 4]
b = a             # 変数bに変数aを格納
print(b is a)            # => True, 変数aと変数bは同じオブジェクト
print(b == a)            # => True,  変数aと変数bに格納されているリスト同じ

b = [1, 2, 3, 4]  # リスト型を作成, [1, 2, 3, 4]
print(b is a)            # => False, 変数aと変数bは別々のオブジェクト
print(b == a)            # => True, 変数aと変数bに格納されているリスト同じ

True
True
False
True

文字列処理

# 文字列の指定は、「"」あるいは「'」でくくる
print("This is a string.")
print('This is also a string.')

This is a string.
This is also a string.

# 文字列の足し算
print("Hello " + "world!")  # => "Hello world!"

# 演算子がなくても可
print("Hello " "world!")    # => "Hello world!"

Hello world!
Hello world!

# 文字列の抽出(スライス操作)
# 1文字目を抽出
print("Hello world!"[0])  # => 'H'

H

# 文字列の長さ
print(len("This is a string"))  # => 16

16

# フォーマット済み文字列リテラル( formatted string literal )または f-string 
name = "Reiko"
print(f"She said her name is {name}.") # => "She said her name is Reiko"

# len関数と組み合わせてみる
print(f"{name} is {len(name)} characters long.") # => "Reiko is 5 characters long."

She said her name is Reiko.
Reiko is 5 characters long.

Nullオブジェクト:None

# Noneの表記
print(None)  # => None

None

# オブジェクトの一致は「is」で確認(==は使わない)
print("etc" is None)  # => False
print(None is None)   # => True

False
True

変数定義

# コンソールから変数を定義
input_string_var = input("Enter some data: ")

# 表示
print(input_string_var)

# 基本的な変数指定
some_var = 5
print(some_var)  # => 5

5

リスト型

定義

# 空リスト
li = []
print(li)

[]

# リスト定義
other_li = [4, 5, 6]
print(other_li)

[4, 5, 6]

# リストを変数に格納
li = [1, 2, 3]
li2 = li[:]

#表示
print(li2)  # => li2 = [1, 2, 3]

[1, 2, 3]

要素を追加

# 空リスト
li = []
print(li)

# 1,2,4,3の順に追加
li.append(1)    # li is now [1]
li.append(2)    # li is now [1, 2]
li.append(4)    # li is now [1, 2, 4]
li.append(3)    # li is now [1, 2, 4, 3]

# 表示
print(li)

[]
[1, 2, 4, 3]

# リスト定義
li=[1,2,3]
print(li)  # => li = [1, 2, 3]

# リストの2番目に4を追加
li.insert(1,4)
print(li)  # => li = [1, 4, 2, 3]

[1, 2, 3]
[1, 4, 2, 3]

要素を除外

# リスト定義
li = [1, 2, 3]

# リストの最後を除外
li.pop()      # => 3 and li is now [1, 2]
print(li)

[1, 2]

# リスト定義
li = [1, 2, 3]

# "del"で2番目の要素を削除
del li[1]
print(li)

[1, 3]

# リスト定義
li = [1, 2, 3]

# リストにある「2」の内「最初の2」を削除
li.remove(2)
print(li)  # li is now [1, 3]

[1, 3]

スライス操作

# 空リスト
li = []
print(li)

# 1,2,4,3の順に追加
li.append(1)    # li is now [1]
li.append(2)    # li is now [1, 2]
li.append(4)    # li is now [1, 2, 4]
li.append(3)    # li is now [1, 2, 4, 3]

# 表示
print(li)

[]
[1, 2, 4, 3]

# リストの1番目
print(li[0])   # => 1
# リストの最後
print(li[-1])  # => 3

1
3

# リストから連続する複数の要素を抽出
# li[start:end:step]
print(li[1:3])   # 2番目から3番目まで  => [2, 4]
print(li[2:])    # 3番目から最後まで  => [4, 3]
print(li[:3])    # 先頭から3番目まで  => [1, 2, 4]
print(li[::2])   # 先頭から1つとばしで3番目まで  => [1, 4]
print(li[::-1])  # 最後から1つとばしで先頭まで  => [3, 4, 2, 1]

[2, 4]
[4, 3]
[1, 2, 4]
[1, 4]
[3, 4, 2, 1]

インデックスの確認

# リストの「2」の内、最初に出てくるインデックスを返す
li = [4, 5, 6]
print(li.index(5))  # =>  1

1

結合

# リスト定義
li1 = [1, 2, 3]
li2 = [4, 5, 6]

# 演算子( + )で結合
print(li1 + li2)  # => [1, 2, 3, 4, 5, 6]

# "extend()"を用いて結合
li1.extend(li2)  # Now li is [1, 2, 3, 4, 5, 6]
print(li1)

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

ある要素が含まれているか確認

# リスト定義
li = [1, 2, 3]
# リスト(li)に1が含まれているかどうか判定
print(1 in li)  # => True

True

長さ

# リスト定義
li = [1, 2, 3]
# リスト(li)の長さを確認
print(len(li))  # => 3

3

タプル型

定義

# タプルの定義
tup = (1, 2, 3)

# 表示
print(tup)

(1, 2, 3)

長さ

# タプルの定義
tup = (1, 2, 3)

# タプルの長さ
print(len(tup))         # => 3

3

結合

# タプルの定義
tup = (1, 2, 3)

# 演算子( + )で結合
print(tup + (4, 5, 6))  # => (1, 2, 3, 4, 5, 6)

(1, 2, 3, 4, 5, 6)

スライス操作

# タプルの定義
tup = (1, 2, 3)

# 1-2番目の要素を表示
print(tup[:2])          # => (1, 2)

(1, 2)

ある要素が含まれているか確認

# タプルの定義
tup = (1, 2, 3)

print(2 in tup)         # => True

True

辞書型

定義

# 空の辞書を定義
empty_dict = {}
print(empty_dict)

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}
print(filled_dict)

{}
{‘one’: 1, ‘two’: 2, ‘three’: 3}

アクセス

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}

# "one"というキーの要素を抽出
print(filled_dict["one"])  # => 1

1

# 含まれている数値データを抽出
print(filled_dict.values())

# 含まれている数値データを抽出し、リスト化
print(list(filled_dict.values()))

dict_values([1, 2, 3])
[1, 2, 3]

# "get()"関数を使って抽出
print(filled_dict.get("one"))      # => 1

1

キーの確認

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}

# キーの確認
print(filled_dict.keys())

# キーをリスト化
print(list(filled_dict.keys()))

dict_keys([‘one’, ‘two’, ‘three’])
[‘one’, ‘two’, ‘three’]

ある要素が含まれているか確認

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}

# キーとして「one」が含まれているか確認
print("one" in filled_dict)  # => True
print(1 in filled_dict)      # => False

True
False

要素を追加

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}

# 辞書に追加
filled_dict.update({"four":4})  # => {"one": 1, "two": 2, "three": 3, "four": 4}
print(filled_dict)

# 次の方法でも追加可能
filled_dict["five"] = 5
print(filled_dict)

{‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4}
{‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4, ‘five’: 5}

要素を削除

# 辞書の定義
filled_dict = {"one": 1, "two": 2, "three": 3}

# "del"で「one」キーを削除
del filled_dict["one"]  # Removes the key "one" from filled dict
print(filled_dict)

{‘two’: 2, ‘three’: 3}

set型

定義

# setの定義
empty_set = set()
print(empty_set)

set()

# 重複した要素は、削除される
some_set = {1, 1, 2, 2, 3, 4}  # some_set is now {1, 2, 3, 4}
print(some_set)

{1, 2, 3, 4}

# 変数を指定して定義
filled_set = some_set
print(filled_set)

{1, 2, 3, 4}

要素を追加

# setを定義
filled_set = {1, 2, 3, 4}

# 要素を追加
filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}
print(filled_set)

{1, 2, 3, 4, 5}

重複する要素の確認

# setを定義
filled_set = {1, 2, 3, 4}
other_set = {3, 4, 5, 6}

# AND
print(filled_set & other_set)  # => {3, 4}

# OR
print(filled_set | other_set)  # => {1, 2, 3, 4, 5, 6}

{3, 4}
{1, 2, 3, 4, 5, 6}

四則演算

# 引き算
print({1, 2, 3, 4} - {2, 3, 5})  # => {1, 4}

{1, 4}

# 累乗(重複していない要素を抽出)
print({1, 2, 3, 4} ^ {2, 3, 5})  # => {1, 4, 5}

{1, 4, 5}

# 比較演算子
print({1, 2} >= {1, 2, 3}) # => False
print({1, 2} <= {1, 2, 3}) # => True

False
True

ある要素が含まれているか確認

# setを定義
filled_set = {1, 2, 3, 4}

# ある要素が辞書に含まれているか確認
print(2 in filled_set)   # => True
print(10 in filled_set)  # => False

True
False

# 変数を別のオブジェクトとしてコピー
filled_set = [1, 2, 3, 4, 5]
filled_set = some_set.copy()  # filled_set is [1, 2, 3, 4, 5]

# 同じオブジェクトか確認
print(filled_set is some_set)        # => False

False

条件処理:If文

# 変数定義
some_var = 5

# If文
# この場合、"some_var is smaller than 10"
if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # This elif clause is optional.
    print("some_var is smaller than 10.")
else:                  # This is optional too.
    print("some_var is indeed 10.")

some_var is smaller than 10.

反復処理:For文

"""
["dog", "cat", "mouse"]のリストを使って
次のように表示したい場合:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # You can use format() to interpolate formatted strings
    print("{} is a mammal".format(animal))

dog is a mammal
cat is a mammal
mouse is a mammal

"""
range関数を使って
次のように表示:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)

0
1
2
3

"""
range関数を使って
次のように表示:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print(i)

4
5
6
7

"""
range関数を使って
次のように4-7まで2飛ばしで表示:
    4
    6
"""
for i in range(4, 8, 2):
    print(i)

4
6

"""
リストのインデックスと値を用いて
次のように表示:
    0 dog
    1 cat
    2 mouse
"""
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value)

0 dog
1 cat
2 mouse

反復処理:While文

"""
x < 4になるまで反復処理をして
次のように表示:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1を意味

0
1
2
3

例外処理

# try/except
try:
    # Use "raise" to raise an error
    raise IndexError("This is an index error")
except IndexError as e:
    pass                 # 例外を無視して、何も処理せず次の処理へ
except (TypeError, NameError):
    pass                 # 複数の例外処理が可能
else:                    # 正常終了時の処理
    print("All good!")   # 例外処理がされず正常に終了した場合に実行
finally:                 # 終了時に常に行う処理
    print("We can clean up resources here")

We can clean up resources here

With文

書き込み

contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
    file.write(str(contents))        # 文字列を書き込み
import json
with open("myfile2.txt", "w+") as file:
    file.write(json.dumps(contents)) # JSON形式で書き込み

読み込み

with open('myfile1.txt', "r+") as file:
    contents = file.read()           # ファイルから文字列を読み込み
print(contents)
# print: {"aa": 12, "bb": 21}

{‘aa’: 12, ‘bb’: 21}

import json
with open('myfile2.txt', "r+") as file:
    contents = json.load(file)       # JSON形式として読み込み
print(contents)
# print: {"aa": 12, "bb": 21}

{‘aa’: 12, ‘bb’: 21}

イテレータ(Iterator)

要素を反復して取り出すことのできるインタフェース

# 辞書を定義
filled_dict = {"one": 1, "two": 2, "three": 3}
# 辞書のキーを取得
our_iterable = filled_dict.keys()
# 表示
print(our_iterable)  # => dict_keys(['one', 'two', 'three'])

dict_keys([‘one’, ‘two’, ‘three’])

# イテレータに変換
our_iterator = iter(our_iterable)

# 一つずつ表示
print(next(our_iterator))  # => "one"
print(next(our_iterator))  # => "two"
print(next(our_iterator))  # => "three"

one
two
three

# イテレータに変換
our_iterator = iter(our_iterable)

# For文でも扱うことが可能
for i in our_iterator:
    print(i)  # Prints one, two, three

one
two
three

# イテレータをリストに変換
print(list(our_iterable))  # => Returns ["one", "two", "three"]

[‘one’, ‘two’, ‘three’]

関数

基本的な使い方

# "def"を使って関数を定義
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y  # Return values with a return statement

# 関数を利用
print(add(5, 6))  # => x=5, y=6なので、"11"を返す

# キーワード(変数)を指定して、引数を与えてもよい
print(add(y=6, x=5))

x is 5 and y is 6
11
x is 5 and y is 6
11

# 2変数を返す関数
def swap(x, y):
    return y, x

x = 1
y = 2
x, y = swap(x, y)     # => x = 2, y = 1
print(x, y)

2 1

# 関数内の変数xは、ローカル変数となる
x = 5

def set_x(num):
    x = num    # => 43
    print(x)   # => 43

def set_global_x(num):
    global x
    print(x)   # => 5
    x = num    # global var x is now set to 6
    print(x)   # => 6

print(set_x(43))
print(set_global_x(6))

43
None
5
6
None

# 関数を入れ子にして定義
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
print(add_10(3))   # => 13

13

可変長引数:args, kwargs

# 可変長引数:args
def varargs(args):
    return args

print(varargs(1, 2, 3))  # => (1, 2, 3), タプル型で返す

(1, 2, 3)

# 可変長引数:kwargs
def keyword_args(kwargs):
    return kwargs

print(keyword_args(big="foot", loch="ness"))  # => {"big": "foot", "loch": "ness"}, 辞書型で返す

{‘big’: ‘foot’, ‘loch’: ‘ness’}

# args, kwargsを同時に使うことも可
def all_the_args(args, kwargs):
    print(args)
    print(kwargs)

print(all_the_args(1, 2, a=3, b=4))

(1, 2)
{‘a’: 3, ‘b’: 4}
None

無名関数:lambda

print((lambda x: x > 2)(3))                  # => True

print((lambda x, y: x  2 + y  2)(2, 1))  # => 5

True
5

関数の繰り返し利用:map

print(list(map(add_10, [1, 2, 3])))          # => [11, 12, 13]

print(list(map(max, [1, 2, 3], [4, 2, 1])))  # => [4, 2, 3]

[11, 12, 13]
[4, 2, 3]

条件抽出

print(list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])))  # => [6, 7]

[6, 7]

内包表記

# リスト型
print([add_10(i) for i in [1, 2, 3]])         # => [11, 12, 13]

print([x for x in [3, 4, 5, 6, 7] if x > 5])  # => [6, 7]

[11, 12, 13]
[6, 7]

# 辞書型
print({x for x in 'abcddeef' if x not in 'abc'})  # => {'d', 'e', 'f'}
print({x: x2 for x in range(5)})  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

{‘e’, ‘d’, ‘f’}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

モジュール(Module)

# モジュールをインポート
import math
print(math.sqrt(16))  # => 4.0

4.0

# 特定の関数をインポート
from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

4
3

# モジュールを別の名前としてインポート
import math as m
print(math.sqrt(16) == m.sqrt(16))  # => True

True

# モジュールに定義されている関数を確認
import math
dir(math)

[‘doc‘,
file‘,
loader‘,
name‘,
package‘,
spec‘,
‘acos’,
‘acosh’,
‘asin’,
‘asinh’,
‘atan’,
‘atan2’,
‘atanh’,
‘ceil’,
‘copysign’,
‘cos’,
‘cosh’,
‘degrees’,
‘e’,
‘erf’,
‘erfc’,
‘exp’,
‘expm1’,
‘fabs’,
‘factorial’,
‘floor’,
‘fmod’,
‘frexp’,
‘fsum’,
‘gamma’,
‘gcd’,
‘hypot’,
‘inf’,
‘isclose’,
‘isfinite’,
‘isinf’,
‘isnan’,
‘ldexp’,
‘lgamma’,
‘log’,
‘log10’,
‘log1p’,
‘log2’,
‘modf’,
‘nan’,
‘pi’,
‘pow’,
‘radians’,
‘remainder’,
‘sin’,
‘sinh’,
‘sqrt’,
‘tan’,
‘tanh’,
‘tau’,
‘trunc’]

クラス(Class)

定義

# "class"でクラスを定義
class Human:

    # クラス属性(attribute). クラス内のすべてのインスタンスで共有される
    species = "H. sapiens"

    # コンストラクタ
    # インスタンスの初期化
    # インスタンスを生成した時に、一度だけ呼び出される
    def __init__(self, name):
        # 引数nameを"name"属性に格納
        self.name = name

        # 初期値の設定
        self._age = 0

    # すべてのメソッドで、"self"が最初に来るように表記
    def say(self, msg):
        print("{name}: {message}".format(name=self.name, message=msg))

    # 他のメソッドを定義
    def sing(self):
        return 'yo... yo... microphone check... one two... one two...'

    # @classmethod:
    # インスタンスを生成しなくてもクラスから直接呼び出すことができるメソッド
    # インスタンスメソッドとは異なり、引数にインスタンスを受け取らないが、かわりにクラスを受け取る。
    @classmethod
    def get_species(cls):
        return cls.species

    # @staticmethod:
    # インスタンスを生成しなくてもクラスから直接呼び出すことができるメソッド
    # クラスやインスタンスなしで呼び出すことができる
    @staticmethod
    def grunt():
        return "grunt"

    # @property
    # 定義したオブジェクトから値を取得したり、更新したり、削除したりしたい時の
    # 動作を定義することができる機能
    @property
    def age(self):
        return self._age

    # プロパティに値を設定
    @age.setter
    def age(self, age):
        self._age = age

    # プロパティを削除
    @age.deleter
    def age(self):
        del self._age
# 定義したクラスや関数を使用して
# 実際に実行した処理を以下に記載

# インスタンス化
i = Human(name="Ian")
print(i.say("hi"))                     # "Ian: hi"
j = Human("Joel")
print(j.say("hello"))                  # "Joel: hello"
# 変数(i,j)は、Humanインスタンスで生成されているため、Humanオブジェクト

# クラスのメソッドを呼び出す
print(i.say(i.get_species()))          # "Ian: H. sapiens"
# クラスの属性を変更
Human.species = "H. neanderthalensis"
print(i.say(i.get_species()))          # => "Ian: H. neanderthalensis"
print(j.say(j.get_species()))          # => "Joel: H. neanderthalensis"

# staticメソッド
print(Human.grunt())            # => "grunt"

# インスタンスでstaticメソッドを呼ぶこともできる
print(i.grunt())                # => "grunt"

# ageプロパティを更新
i.age = 42
# プロパティの取得
print(i.say(i.age))                    # => "Ian: 42"
print(j.say(j.age))                    # => "Joel: 0"
# プロパティの削除
del i.age

Ian: hi
None
Joel: hello
None
Ian: H. sapiens
None
Ian: H. neanderthalensis
None
Joel: H. neanderthalensis
None
grunt
grunt
Ian: 42
None
Joel: 0
None

継承

# 引数に親クラスを指定
class Superhero(Human):

    # 親クラスのspecies属性を変更
    species = 'Superhuman'

    # 子クラスのコンストラクタは、親クラスから引き継がれる
    # 更新・追加することも可能
    # 親クラスからname引数を継承して、"superpower", "movie"引数を追加 
    def __init__(self, name, movie=False,
                 superpowers=["super strength", "bulletproofing"]):

        # 属性の追加
        self.fictional = True
        self.movie = movie
        self.superpowers = superpowers

        # "super"関数で親クラスのメソッドを継承
        super().__init__(name)

    # singメソッドを上書き
    def sing(self):
        return 'Dun, dun, DUN!'

    # 追加のインスタンス
    def boast(self):
        for power in self.superpowers:
            print("I wield the power of {pow}!".format(pow=power))
# 定義したクラスや関数を使用して
# 実際に実行した処理を以下に記載

# インスタンス化
sup = Superhero(name="Tick")

# インスタンスのタイプをチェック
if isinstance(sup, Human):
    print('I am human')
if type(sup) is Superhero:
    print('I am a superhero')

# メソッド順序解決(MRO)を確認
print(Superhero.__mro__)    # => (<class '__main__.Superhero'>,
                            # => <class 'human.Human'>, <class 'object'>)

# 親クラスから継承したメソッドを利用
print(sup.get_species())    # => Superhuman

# 上書きしたメソッドを利用
print(sup.sing())           # => Dun, dun, DUN!

# 親クラスのメソッドを利用
sup.say('Spoon')            # => Tick: Spoon

# 子クラスで追加したメソッドを利用
sup.boast()                 # => I wield the power of super strength!
                            # => I wield the power of bulletproofing!

# 継承した属性を更新
sup.age = 31
print(sup.age)              # => 31

# 子クラスで追加した属性
print('Am I Oscar eligible? ' + str(sup.movie))

I am human
I am a superhero
(, , )
Superhuman
Dun, dun, DUN!
Tick: Spoon
I wield the power of super strength!
I wield the power of bulletproofing!
31
Am I Oscar eligible? False

複数の継承

# Batというクラスを定義
class Bat:

    species = 'Baty'

    def __init__(self, can_fly=True):
        self.fly = can_fly

    # メソッドを定義
    def say(self, msg):
        msg = '... ... ...'
        return msg

    # 追加のメソッドを定義
    def sonar(self):
        return '))) ... ((('

if __name__ == '__main__':
    b = Bat()
    print(b.say('hello'))
    print(b.fly)


# Batmanクラスを"Superhero"クラスと"Bat"クラスを継承して定義
class Batman(Superhero, Bat):

    def __init__(self, args, kwargs):
        # 通常、属性を継承するために、"super"を呼び出す必要があるが
        # 多重継承をしているので、次の基底クラスで継承可
        Superhero.__init__(self, 'anonymous', movie=True,
                           superpowers=['Wealthy'], args, kwargs)
        Bat.__init__(self, args, can_fly=False, kwargs)
        # name属性を上書き
        self.name = 'Sad Affleck'

    def sing(self):
        return 'nan nan nan nan nan batman!'

… … …
True

# 定義したクラスや関数を使用して
# 実際に実行した処理を以下に記載

# インスタンス化
sup = Batman()

# メソッド順序解決(MRO)を確認
print(Batman.__mro__)       # => (<class '__main__.Batman'>,
                            # => <class 'superhero.Superhero'>,
                            # => <class 'human.Human'>,
                            # => <class 'bat.Bat'>, <class 'object'>)

# 継承したクラス属性
print(sup.get_species())    # => Superhuman

# 上書きしたメソッドを利用
print(sup.sing())           # => nan nan nan nan nan batman!

# 継承したメソッド
print(sup.say('I agree'))          # => Sad Affleck: I agree

# 第2祖先から継承したメソッド
print(sup.sonar())          # => ))) ... (((

# 継承した属性を更新
sup.age = 100
print(sup.age)              # => 100

# 2番目の祖先から継承した属性
print('Can I fly? ' + str(sup.fly)) # => Can I fly? False

(, , , , )
Superhuman
nan nan nan nan nan batman!
Sad Affleck: I agree
None
))) … (((
100
Can I fly? False

Print Friendly, PDF & Email

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください