# How can *= be a function?

#1

How can *= be a function?

#2

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``

#3

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
print(a)``````

Output:

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

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

#4

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