2014年5月4日日曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅵ.(Classes and OOP)、CHAPTER 32(Advanced Class Topics)、Test Your Knowledge: Part VI Exercises 2.(Operator overloading)を解いてみる。

その他参考書籍

2.(Operator overloading)

コード(BBEdit)

sample.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

class MyList:
    def __init__(self, data=[]):
        self.data = list(data)
    def __add__(self, other):
        if isinstance(other, MyList):
            other = other.data
        return MyList(self.data + other)
    def __radd__(self, other):
        return MyList(other + self.data)
    def __getitem__(self, i):
        return self.data[i]
    def append(self, other):
        self.data.append(other)
    def sort(self,key=None, reverse=False):
        self.data.sort(key=key, reverse=reverse)
    def __getattr__(self, name):
        return getattr(self.data, name)
    def __repr__(self):
        return 'MyList: {0}'.format(self.data)
    
if __name__ == '__main__':
    o1 = MyList([1,2,3,4,5])
    o2 = MyList([6, 7])
    l = [10, 100]
    print(o1 + o2)
    print(o2 + o1)
    print(o1 + l)
    print(l + o1)
    print(o1[2])
    print(o1[:])
    o1 += [1000]
    print(o1)
    o1.append(50)
    print(o1)
    o1.sort()
    print(o1)
    print(o1.pop())
    print(o1)
    for x in o1:
        print(x)
    s = MyList('python')
    print(s)

入出力結果(Terminal)

$ ./sample.py
MyList: [1, 2, 3, 4, 5, 6, 7]
MyList: [6, 7, 1, 2, 3, 4, 5]
MyList: [1, 2, 3, 4, 5, 10, 100]
MyList: [10, 100, 1, 2, 3, 4, 5]
3
[1, 2, 3, 4, 5]
MyList: [1, 2, 3, 4, 5, 1000]
MyList: [1, 2, 3, 4, 5, 1000, 50]
MyList: [1, 2, 3, 4, 5, 50, 1000]
1000
MyList: [1, 2, 3, 4, 5, 50]
1
2
3
4
5
50
MyList: ['p', 'y', 't', 'h', 'o', 'n']
$

0 コメント:

コメントを投稿