python - __rmul__ call under what circumstances?

 
In the custom list Mylist after, 3 * Mylist error, Mylist * already overloaded, but no 3, when students told me available __ rmul __
 
 
Say I have a list l. Under what circumstances l .__ rmul __ (self, other) called?

 

I basically understand the document, but I also want to see an example to clarify its use, no doubt.

 
When multiplied by the Python tries to two objects, it first tries to __mul __ () method is called the left object. If the object is not left __mul __ () method (or method returns NotImpemented, indicating that it does not apply to the right operand), Python would like to know whether the correct object can be multiplied. If the same type of the right operand and the left, Python knows that it can not, because if the object can not be left to do, another object of the same type can not be sure.

 

If two objects of different types, Python, this is worth a try. However, it needs some way to tell the correct object it is operating in the correct object, if the operation is not commutative. (Multiplication, of course, but not all operators are, in any case * for multiplication is not always!) So it calls __rmul __ () instead __mul __ ().

For example, consider the following two statements:

 

print "nom" * 3
print 3 * "nom"

In the first case, Python string __mul __ call () method. Know how to string itself is multiplied by an integer, so all is well. In the second case, an integer multiplied by itself does not know how to use a string, so it's __mul () __ return NotImplemented, and __rmul string () __ is called. It knows what to do, and you get the same result as the first case.

Now we can see, __ rmul () __ allow all the strings of special multiplier acts included in the str class, so other types (such as integers) do not need to know anything about the string of data, so that they can be multiplied. One hundred years later (assuming that Python is still in use), you will be able to define a new type, you can take any sequence of integers, even if int class has been known for over a century.

Incidentally, __mul __ string class () has a bug in some versions of Python. If it does not know how an object multiplied by itself, it raises a TypeError, instead of returning NotImplemented. This means that even if a user-defined type has __rmul __ () method, nor can the string multiplied by the user-defined types, because it does not allow the string from the opportunity. User-defined types must first (e.g. Foo () * 'bar' and not 'bar' * Foo ()), so it __mul __ () is called. They seem to have been fixed in Python 2.7 (I tested it in Python 3.2), but Python 2.6.6 errors.

Guess you like

Origin www.cnblogs.com/LLbinGG/p/11135881.html