2014年4月23日水曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅵ.(Classes and OOP)、CHAPTER 30(Operator Overloading)、Test Your Knowledge: Quiz.1.~5.を解いてみる。

その他参考書籍

Test Your Knowledge: Quiz.1.~5.

    • __getitem__
    • __iter__
    • __repr__
    • __str__
  1. コード(BBEdit)

    sample.py

    #!/usr/bin/env python3
    #-*- coding: utf-8 -*-
    
    class Slicing:
        data = list(range(0, 10))
        def __getitem__(self, index):
            if isinstance(index, int):
                return self.data[index - 1]
            return self.data[index.start:index.stop:index.step]
        def __repr__(self):
            return repr(self.data)
    
    o = Slicing()
    
    for x in [o, o[1], o[5], o[:], o[2:], o[:5], o[2:5]]:
        print(x)
    

    入出力結果(Terminal)

    $ ./sample.py
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    0
    4
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    [2, 3, 4, 5, 6, 7, 8, 9]
    [0, 1, 2, 3, 4]
    [2, 3, 4]
    $
    
  2. コード(BBEdit)

    sample.py

    #!/usr/bin/env python3
    #-*- coding: utf-8 -*-
    
    class InPlaceAdd1:
        def __init__(self, data):
            self.data = data
        def __add__(self, other):
            return self.data + other
        def __repr__(self):
            return repr(self.data)
    
    class InPlaceAdd2:
        def __init__(self, data):
            self.data = data
        def __add__(self, other):
            return self.data + other
        def __iadd__(self, other):
            self.data += 1
            return self
        def __repr__(self):
            return repr(self.data)
    
    class InPlaceAdd3:
        def __init__(self, data):
            self.data = data
        def __add__(self, other):
            return self.data + other
        def __iadd__(self, other):
            self.data = 'Hello, __iadd__ world!'
            return self
        def __repr__(self):
            return repr(self.data)
    
    o1 = InPlaceAdd1(10)
    o2 = InPlaceAdd2(10)
    o3 = InPlaceAdd3(10)
    
    print(o1, o2, o3)
    o1 += 5
    o2 += 5
    o3 += 5
    print(o1, o2, o3)
    o1 += 5
    o2 += 5
    o3 += 5
    print(o1, o2, o3)
    

    入出力結果(Terminal)

    $ ./sample.py
    10 10 10
    15 11 'Hello, __iadd__ world!'
    20 12 'Hello, __iadd__ world!'
    $
    
  3. 作成したクラスに、ビルトインクラスのように、自然な演算子を用意したいときに、演算子をオーバーロードするといい。(不自然な振る舞いの演算子を、演算子のオーバーロードによって用意するべきではない。)

0 コメント:

コメントを投稿