# 特殊方法名稱

``class Rational:    def __init__(self, n, d):  # 物件建立之後所要建立的初始化動作        self.numer = n        self.denom = d        def __str__(self):   # 定義物件的字串描述        return str(self.numer) + '/' + str(self.denom)        def __add__(self, that):  # 定義 + 運算        return Rational(self.numer * that.denom + that.numer * self.denom,                         self.denom * that.denom)        def __sub__(self, that):  # 定義 - 運算        return Rational(self.numer * that.denom - that.numer * self.denom,                        self.denom * that.denom)                               def __mul__(self, that):  # 定義 * 運算        return Rational(self.numer * that.numer,                         self.denom * that.denom)            def __truediv__(self, that):   # 定義 / 運算        return Rational(self.numer * that.denom,                        self.denom * that.denom)    def __eq__(self, that):   # 定義 == 運算        return self.numer * that.denom == that.numer * self.denomx = Rational(1, 2)y = Rational(2, 3)z = Rational(2, 3)print(x)       # 1/2print(y)       # 2/3print(x + y)   # 7/6print(x - y)   # -1/6print(x * y)   # 2/6print(x / y)   # 3/6print(x == y)  # Falseprint(y == z)  # True``

__str__()用來定義傳回物件描述字串，通常用來描述的字串是對使用者友善的說明文字，如果對物件

>>> class Some:
...     def __setattr__(self, name, value):
...         print(name, value)
...     def __init__(self):
...         self.x = 10
...
>>> s = Some()
x 10
>>> s.w = 100
w 100
>>> s.__dict__['z'] = 200
>>> print(s.__dict__)
{'z': 200}
>>>

__getitem__()__setitem__()則用來設定[]運算子的行為。例如：

>>> class Some:
...     def __init__(self):
...         self.inner = {}
...     def __setitem__(self, name, value):
...         self.inner[name] = value
...     def __getitem__(self, name):
...         return self.inner[name]
...
>>> s = Some()
>>> s[0] = 100
>>> s['Justin'] = 'Message'
>>> s[0]
100
>>> s['Justin']
'Message'
>>>

``class Some:    class Iterator:        def __init__(self, length):            self.length = length            self.number = -1        def __next__(self):            self.number = self.number + 1            if self.number == self.length:                raise StopIteration            return self.number        def __init__(self, length):        self.length = length    def __iter__(self):        return Some.Iterator(self.length)s = Some(3)it = iter(s)print(next(it))   # 0print(next(it))   # 1print(next(it))   # 2print(next(it))   # StopIteration``

for n in Some(10):
print(n)       # 顯示 0 到 9