How can *= be a function?


How can *= be a function?

Reassign in a single line

It invokes a built-in function that amalgamates one value into another. If that isn't a function then I'm gone off.

Let's think on it.

A and B are some quantities, A is cummulative, and B is variable.

A *= B

Let's say * is a function.

def *(a,b):
    return a * b

What we're really telling the interpreter is,

A = A * B


Specifically it's defined by the __imul__ attribute of the value on the left side:

class MyValueType(object):
    def __init__(self, val):
        if not isinstance(val, int):
            raise ValueError('an integer is required')
        self.val = val

    def __imul__(self, other):
        print('{!r}.__imul__({!r}) was invoked!'.format(self, other))
        self.val = self.val * other.val
        return self

    def __repr__(self):
        return 'MyValueType({})'.format(self.val)

a = MyValueType(3)
b = MyValueType(5)
a *= b


MyValueType(3).__imul__(MyValueType(5)) was invoked!

Also, *= is not always equivalent to using = and *, because * uses __mul__ instead of __imul__. The i in imul stands for in-place, so if the value is mutable then the multiplication happens in-place, as opposed to creating a new value like __mul__ does


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.