我是一名python初学者,正在阅读有关Dunder方法的文章。是否可以以某种方式更改int或str等类的dunder方法
例如,我可以以某种方式改变int类的dunder方法__add__来执行乘法而不是加法吗?所以如果我输入3+ 4,输出是12?
发布于 2021-01-05 23:48:00
你可以子类化,但值得指出的是,这可能是一个糟糕的想法,因为没有人合理地期望add执行乘法:
class FunkyInt(int):
def __add__(self, other):
return FunkyInt(self * other)
f = FunkyInt(3)
print(f + 4)
# 12https://stackoverflow.com/questions/65582036
复制相似问题