モジュールのレッスン (3/4)
特殊な方法(ダンダー)
特別なメソッド (始まりと終わりがあるため、ダンダー メソッドと呼ばれます)
二重アンダースコア付き: __name__) は、オブジェクトを
言語との統合: テキスト表現、== との比較、
len()、in、演算子などのサポート。
__init__ はすでに使用されています。
__str__ および __repr__
これらは、print() および REPL で表示される内容を制御します。
class Punto:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Punto({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Punto(3, 4)
str(p) # '(3, 4)' — per umani
repr(p) # 'Punto(3, 4)' — per debugger / dev
print(p) # '(3, 4)'
p # Punto(3, 4) in REPL → repr
[p, p] # [Punto(3, 4), Punto(3, 4)] — sempre repr nei contenitori__repr__ のみを定義した場合、Python はそれをフォールバックとしても使用します。
__str__。
__eq__: == の再定義
デフォルトでは、a == b はオブジェクト (is) の 識別子 を比較します。
それらの内容。構造を比較するには、__eq__ を定義します。
class Punto:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
if not isinstance(other, Punto):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
Punto(1, 2) == Punto(1, 2) # True
Punto(1, 2) == Punto(3, 4) # Falseタイプが次の場合、NotImplemented (False ではなく特別なキーワード!) を返します。
比較できないのは正しい方法です。Python は次に、
他のオペランドの __eq__。
__len__: len() のサポート
class Cesto:
def __init__(self):
self.frutti = []
def __len__(self):
return len(self.frutti)
c = Cesto()
c.frutti.append("mela")
len(c) # 1
bool(c) # True (len > 0)__len__ を定義すると、boolean というオブジェクトも無料で取得できます。
len() == 0 を使用すると false になります。
その他の便利なダンダー (概要)
__add__(self, other)→+を再定義します__lt__、__le__、__gt__、__ge__→ 比較演算子__contains__(self, item)→item in selfをサポート__iter__+__next__→ オブジェクトを反復可能にします__getitem__(self, key)→self[key]をサポート__hash__→ 辞書キー/セット要素である必要があります
あなたの番です
__init__(self, amount,currency) と `f'{amount} {currency}'` を返す __str__ を使用して `Money` を定義します。 `s = Money(42, 'EUR')` を作成し、`str(s)` を評価します。
ヒントを表示
__str__ の f 文字列。
3 回の試行後に解決策が利用可能になります
復習演習
(a, b) の構造比較に基づいて __init__(self, a, b) と __eq__ の `Pair` を定義します。 `Pair(1, 2) == ペア(1, 2)` を評価します。
ヒントを表示
タプル (self.a, self.b) == (other.a, other.b) を比較します。
3 回の試行後に解決策が利用可能になります
追加の課題
\`title\` と \`author\` を受け取るコンストラクターを使用してクラス \`Book\` を定義します。特別なメソッド \`__str__(self)\` を定義して、文字列 \`"Title by Author"\` (例: \`'1984 by George Orwell'\`) を返します。 book をインスタンス化し、\`str(book)\` を評価します。
ヒントを表示
def __str__(self): 内で f"{self.title} by {self.author}" を使用します。
3 回の試行後に解決策が利用可能になります