How to change connected class objects

37 Views Asked by At

My code:

class Potato:
    def __init__(self, r):
        self.size = r

    def __itruediv__(self, other):
        self.size /= other
        return Potato(self.size)

    def __truediv__(self, other):
        a = self.size
        self.size -= self.size / other
        return Potato(a / other)

    def __str__(self):
        return f"Potato({self.size})"
pt = pt1 = Potato(7)
pt /= 4
print(pt)
pt2 = pt / 3
print(pt, pt1, pt2, sep='\n')

Output:

Potato(1.75)
Potato(1.1666666666666665)
Potato(1.75)
Potato(0.5833333333333334)

Need Output:

Potato(1.75)
Potato(1.1666666666666665)
Potato(1.1666666666666665)
Potato(0.5833333333333334)

I don't know, why pt1 don't have same output as pt? and how to solve it. Please help

1

There are 1 best solutions below

0
Barmar On BEST ANSWER

The in-place operators should normally return the object that was modified. The return value is assigned to the variable, so if it returns a new object the variable will be reassigned. Because of this, after

pt /= 4

pt and pt1 no longer refer to the same Potato instance.

Conversely, the regular arithmetic operators should not normally modify their arguments, they should just return a new object. So __truediv__() should not reassign self.size.

class Potato:
    def __init__(self, r):
        self.size = r

    def __itruediv__(self, other):
        self.size /= other
        return self

    def __truediv__(self, other):
        a = self.size / other
        return Potato(a)

    def __str__(self):
        return f"Potato({self.size})"

pt = pt1 = Potato(7)
pt /= 4
print(pt)
pt2 = pt / 3
print(pt, pt1, pt2, sep='\n')