Python リストを合成したクラス

#関数とメソッドの違いってなに?より
#
# 対話モード >>> に
# コピペで実行できます。
#
class Container:
    def __init__(self, *args):
        self._values = args
    
    def __getitem__(self, index):
        return self._values[index]
    
    def __iter__(self):
        return iter(self._values)
    
    def __len__(self):
        return len(self._values)

container = Container(0, 1, 2)


# 1) 直接、添字表記で参照できる。
container[0]
container[1]
container[2]

# 2) 直接、for 文で回せる。
for element in container:
    element

# 3) 直接、len 関数でオブジェクトの長さを取得できる。
len(container)

>>> # 1) 直接、添字表記で参照できる。
... container[0]
0
>>> container[1]
1
>>> container[2]
2
>>> 
>>> # 2) 直接、for 文で回せる。
... for element in container:
...     element
... 
0
1
2
>>> # 3) 直接、len 関数でオブジェクトの長さを取得できる。
... len(container)
3
>>> 

class Container(tuple):
    def __new__(cls, *args):
        return super().__new__(cls, args)

container = Container(0, 1, 2)


# 1) 直接、添字表記で参照できる。
container[0]
container[1]
container[2]

# 2) 直接、for 文で回せる。
for element in container:
    element

# 3) 直接、len 関数でオブジェクトの長さを取得できる。
len(container)

コメント

このブログの人気の投稿

Python OpenCVとWebカメラでバーコードリーダー

OpenCV 画像の足し算

OpenCV3とPython3で形状のある物体の輪郭と方向を認識する(主成分分析:PCA、固有ベクトル)