考慮一個支持強制轉換為字串的類,并且add當第二個運算元是字串時支持連接(Python):
$ cat dunder.py
class Foo:
def __str__(self):
return "foo"
def __add__(self, second):
return str(self) str(second)
f = Foo()
print(f)
print(f "bar")
print("bar" f)
和方法按預期輸出到螢屏print(f)。print(f "bar")但是,該print("bar" f)方法按預期拋出例外:
$ python3 dunder.py
foo
foobar
Traceback (most recent call last):
File "dunder.py", line 12, in <module>
print("bar" f)
TypeError: can only concatenate str (not "Foo") to str
str當類的 dunder 方法執行連接時,如何修改類以支持字串連接?
請注意,我不想擴展str類,我對一般情況感興趣。
uj5u.com熱心網友回復:
您需要實作方法,這是一個右側添加,在標準失敗__radd__時用作后備。__add__它在添加操作中在右側物件上呼叫,左側物件是它的另一個引數,因此您需要以相反的順序執行連接。
class Foo:
def __str__(self):
return "foo"
def __add__(self, second):
return str(self) str(second)
def __radd__(self, second):
return str(second) str(self)
f = Foo()
print(f)
print(f "bar")
print("bar" f)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518013.html
