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

2024-05-13 03:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我要做的是创建一个类来包装int,并允许一些int类型通常不允许的事情。我真的不在乎它是不是Python或w/e我只是在寻找结果。这是我的代码:

^{1}$

结果是。在

^{pr2}$

所以,第一个print语句运行得很好,并且给出了我所期望的结果,但是第二个语句给出了一个错误。我认为这是因为第一个函数使用了tInt的add函数,因为a出现在+“5”之前;第二个函数首先使用字符串“5”的add函数,因为它首先出现。我知道这一点,但我真的不知道如何强制a的add函数,或者允许将tInt类表示为string/int/等等。。当正常类型在操作中出现在它前面时。在


Tags: 函数字符串代码add类型string错误语句
1条回答
网友
1楼 · 发布于 2024-05-13 03:37:11

您需要实现一个__radd__方法来处理当类的实例位于加法的右侧时的情况。在

docs说:

These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. 2 For instance, to evaluate the expression x - y, where y is an instance of a class that has an rsub() method, y.rsub(x) is called if x.sub(y) returns NotImplemented.

示例:

class tInt(int):

    def __add__(self, other):
        if isinstance(other, str):
            return str(self) + str(other)
        elif isinstance(other, int):
            return int(self) + other
        elif isinstance(other, float):
            return float(self) + float(other)
        else:
            return NotImplemented

    def __radd__(self, other):
        return self.__add__(other) 

a = tInt(2)
for x in ["5", 5, 5.0]:
    print (a + x)
    print (x + a)

25
25

7
7

7.0
7.0

正如@chepner在注释中指出的那样,如果您的方法无法处理返回NotImplemented,则会导致Python尝试其他方式执行该操作,或者在无法执行请求的操作时引发TypeError。在

相关问题 更多 >