所以我想要做的是创建一个包装int的类,并允许一些通常不允许使用int类型的东西.我真的不在乎它不是pythonic还是w/e我只是在寻找结果.这是我的代码:
class tInt(int):
def __add__(self, other):
if type(other) == str:
return str(self) + str(other)
elif type(other) == int:
return int(self) + other
elif type(other) == float:
return float(self) + float(other)
else:
return self + other
a = tInt(2)
print (a + "5")
print ("5" + a)
Run Code Online (Sandbox Code Playgroud)
输出是.
>> 25
Traceback (most recent call last):
File "C:\example.py", line 14, in <module>
print ("5" + a)
TypeError: Can't convert 'tInt' object to str implicitly
Run Code Online (Sandbox Code Playgroud)
所以,第一个print语句运行良好,并给出了我的预期,但第二个给出了错误.我认为这是因为第一个使用tInt的add函数,因为a出现在+"5"之前,而第二个使用字符串"5"的add函数,因为它首先出现.我知道这一点,但我真的不知道如何强制一个add函数或者允许tInt类表示为字符串/ int/etc …
所以,我想要做的是将一个浮点数转换为一个bytearray,但我继续接收无输入,并且EXTREME减慢/冻结我的计算机.我的代码是
import struct
def float_to_hex(f):
return hex(struct.unpack('<I', struct.pack('<f', f))[0])
value = 5.1 #example value
...
value = bytearray(int(float_to_hex(float(value)), 16)
Run Code Online (Sandbox Code Playgroud)
我在另一篇文章中找到了一个将浮点数转换为十六进制的函数
def float_to_hex(f):
return hex(struct.unpack('<I', struct.pack('<f', f))[0])
Run Code Online (Sandbox Code Playgroud)
然后我将它从十六进制转换为int.这有什么问题?我怎么能更好地将它从浮点数转换为bin或bytearray?