Tuple(タプル)
Tuple で 3つの値 を返す関数のサンプルコード
次のサンプルコードは getData関数 から 3つの値「'text', 100, True」を返し、表示します。# Tupleで結果を返す関数
def getData():
return ('text', 100, True)
# 関数の呼び出し
result = getData()
# 結果の表示
print(result[0]) # 結果 = 'text'
print(result[1]) # 結果 = 100
print(result[2]) # 結果 = True
解説
Tuple(タプル) とは、複数のオブジェクト を格納できるコンテナ型です。 カンマ区切り で値を並べると Tuple を返します。Tupleは イミュータブル のため、作成後に値の追加や変更はできません。Tuple = (オブジェクト, オブジェクト)
Tuple = (オブジェクト, オブジェクト, オブジェクト)
Tuple = オブジェクト, オブジェクト
Tuple = オブジェクト, オブジェクト, オブジェクト
- 小括弧「()」は省略できます。
1番目のオブジェクト = Tuple[0]
2番目のオブジェクト = Tuple[1]
型ヒント(typing)付き
型ヒントについては Python - 型ヒント(typing)の一覧 を参照してください。# 型ヒント(typing)付き
def getData() -> tuple[str, int, bool]:
return ('text', 100, True)
dataclass(データクラス)
dataclass で 3つの値 を返す関数のサンプルコード
from dataclasses import dataclass
# GetDataResult の名前で dataclass を定義
@dataclass
class GetDataResult:
# メンバ変数の定義
name: str
score: int
isSuccess: bool
# dataclass で 結果を返す関数
def getDate() -> GetDataResult:
# GetDataResult型のインスタンスを生成
result = GetDataResult(name='', score=0, isSuccess=False)
# dataclass は値の変更ができる
result.name = 'text'
result.score = 100
result.isSuccess = True
# 戻り値を返す
return result
# 関数の呼び出し
result = getDate()
# 結果の表示
print(result.name) # 結果 = 'text'
print(result.score) # 結果 = 100
print(result.isSuccess) # 結果 = True
解説
class に対して 型アノテーション @dataclass を指定すると、メンバ変数 を引数とするコンストラクタ (__init__ メソッド)が自動で作成されます。自動で追加されるコンストラクタが不要なときは @dataclass の指定をやめるか、型アノテーション の 引数 init に False を指定します。コンストラクタの自動生成をせずに dataclass を定義
from dataclasses import dataclass
# コンストラクタの自動生成をせずに dataclass を定義
@dataclass(init=False)
class GetDataResult:
name: str
score: int
isSuccess: bool
# dataclass で 結果を返す関数
def getDate() -> GetDataResult:
# GetDataResult型のインスタンスを生成
result = GetDataResult()
# 返したい値の代入
result.name = 'text'
result.score = 100
result.isSuccess = True
# 戻り値を返す
return result
通常の class 定義
class GetDataResult:
# コンストラクタ
def __init__(self):
# インスタンス変数の定義
self.name = ''
self.score = 0
self.isSuccess = False
参考資料
検証環境
- Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.3570 Experience: Windows Feature Experience Pack 1000.19052.1000.0