我正在尝试将一个int和class一起添加,例如1 + Currency(1) 我收到错误消息:TypeError:+不支持的操作数类型:“ int”和“ Currency”
如果我使用Currency(1)+ 1,它将正常工作。
是否有某种方法可以将int转换为类对象?还是需要将类转换为int对象?
class Currency:
"A general currency class"
def __init__(self, kr=0, ore=0):
"Input kr and ore, with default values 0"
self.ore = round(ore + (kr * 100), 0)
self.kr = int(self.ore / 100)
kr_ore = kr + ore / 100
def __add__(self, other):
self, other = Currency.__check_type(self, other)
print(type(self), type(other))
total = self.ore + other.ore
self.kr = int(total / 100)
self.ore = total - self.kr * 100
return Currency(self.kr, self.ore)
def __check_type(self, other):
if type(self) != Currency and type(int) != Currency:
self = Currency(self)
other = Currency(other)
elif type(self) != Currency:
print("RUNNING")
self = Currency(self)
elif type(other) != Currency:
other = Currency(other)
return self, other
__repr__ = __str__
x = 100
y = Currency(1)
print(x+y)
答案 0 :(得分:4)
您几乎做到了,如果您打印y+x
,它将对您的代码有效。
__add__
用于+
运算符左侧的对象,右边的dunder方法称为__radd__
。
class Currency:
"A general currency class"
def __init__(self, kr=0, ore=0):
"Input kr and ore, with default values 0"
self.ore = round(ore + (kr * 100), 0)
self.kr = int(self.ore / 100)
kr_ore = kr + ore / 100
def __add__(self, other):
self, other = Currency.__check_type(self, other)
print(type(self), type(other))
total = self.ore + other.ore
self.kr = int(total / 100)
self.ore = total - self.kr * 100
def __radd__(self, other):
self, other = Currency.__check_type(self, other)
print(type(self), type(other))
total = self.ore + other.ore
self.kr = int(total / 100)
self.ore = total - self.kr * 100
return Currency(self.kr, self.ore)
def __check_type(self, other):
if type(self) != Currency and type(int) != Currency:
self = Currency(self)
other = Currency(other)
elif type(self) != Currency:
print("RUNNING")
self = Currency(self)
elif type(other) != Currency:
other = Currency(other)
return self, other
x = 100
y = Currency(1)
print(x+y)