相关疑难解决方法(0)

用户定义类的自动类型转换

所以我想要做的是创建一个包装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 …

python python-3.x

8
推荐指数
1
解决办法
770
查看次数

标签 统计

python ×1

python-3.x ×1