特殊属性、メソッド、演算子
□未翻訳
□翻訳中
□翻訳完了(細田謙二)
■レビュー(Omi Chiba)
特殊属性、メソッド、演算子
2つのアンダスコアから始まるクラス属性、メソッド、演算子は、一般にプライベートであることを意図しますが、これはインタプリタによって強制される慣例ではありません。
Class attributes, methods, and operators starting with a double underscore are usually intended to be private, although this is a convention that is not enforced by the interpreter.
そのうちのいくつかは予約されたキーワードで、特別な意味を持っています。
Some of them are reserved keywords and have a special meaning.
例として、そのなかの3つを示します。
Here, as an example, are three of them:
__len__
__getitem__
__setitem__
これらは、たとえば、リストのように振舞うコンテナオブジェクトの作成に利用できます:
They can be used, for example, to create a container object that acts like a list:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
>>> class MyList(object)
>>> def __init__(self, *a): self.a = a
>>> def __len__(self): return len(self.a)
>>> def __getitem__(self, i): return self.a[i]
>>> def __setitem__(self, i, j): self.a[i] = j
>>> b = MyList(3, 4, 5)
>>> print b[1]
4
>>> a[1] = 7
>>> print b.a
[3, 7, 5]
他の特殊演算子としては、クラスにおいて属性の取得と設定を定義する__getattr__と__setattr__や、算術演算子をオーバーロードする__sum__や__sub__などがあります。 これらの演算子の利用についてもっと知りたい場合は、より高度な書籍を参照してください。また、__str__と__repr__演算子についてはすでに言及してあります。
Other special operators include __getattr__ and __setattr__, which define the get and set attributes for the class, and __sum__ and __sub__, which overload arithmetic operators. For the use of these operators we refer the reader to more advanced books on this topic. We have already mentioned the special operators __str__ and __repr__.