如何添加我的自定义 class 的两个实例

How to add two instances of my custom class

我想要 运行 此代码 (必须)包括 printtotal 旁边的属性 value部分。我应该在 class 中插入什么代码才能做到这一点?

class Random:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return self.x + other.x


p1 = Random(2)
p2 = Random(3)

total = p1 + p2

print(total.value)

也将 total 设为 Random

class Random:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return Random(self.value + other.value)


p1: Random = Random(2)
p2: Random  = Random(3)

total: Random = p1 + p2

print(total.value)

Return 在您的 __add__ 方法中创建 Random 的实例,并为 class 添加名称为 value 的 属性。

class Random:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return Random(self.x + other.x)

    @property
    def value(self):
        return self.x


p1 = Random(2)
p2 = Random(3)

total = p1 + p2

print(total.value)

当然,更好的选择是将实例属性 x 替换为 value。那么就不需要 属性.

class Random:
    def __init__(self, x):
        self.value = x

    def __add__(self, other):
        return Random(self.value + other.value)