Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define method aliases in Python?

Tags:

I have a vector class and I defined the __mul__ method to multiply a vector by a number.

Here is the __mul__ method :

def __mul__(self, other):     x = self.x * other     y = self.y * other     new = Vector()     new.set_pos((x, y))     return new 

My problem is that I don't know which is which between the number and the vector. If self is the number, self.x raises an error. (I'm maybe mistaking on this point : Is "other" always a number ?)

So I found here : Python: multiplication override that I could do :

__rmul__ = __mul__ 

but how can I do that in a class definition ?

Something like :

def __rmul__ = __mul__ 
like image 861
Zoé Martin Avatar asked Jun 29 '12 15:06

Zoé Martin


People also ask

What are aliases in Python?

In python programming, the second name given to a piece of data is known as an alias. Aliasing happens when the value of one variable is assigned to another variable because variables are just names that store references to actual value.

What is aliasing in list give an example?

In Python, aliasing happens whenever one variable's value is assigned to another variable, because variables are just names that store references to values. For example, if first refers to the string 'isaac' …

What is an alias in code?

1) In some computer operating systems and programming languages, an alias is an alternative and usually easier-to-understand or more significant name for a defined data object. The data object can be defined once and later a programmer can define one or more equivalent aliases that will also refer to the data object.


1 Answers

self will never be the number in __mul__() because the object the method is attached to is not the number, it's the vector, and by definition it's the multiplicand.

other will be a number if your object is being multiplied by a number. Or it could be something else, such as another vector, which you could test for and handle.

When your object is the multiplier, __rmul__() is called if the multiplicand doesn't know how to handle the operation.

To handle the case in which __mul__ and __rmul__ should be the same method, because the operation is commutative, you can just do the assignment in your class definition.

class Vector(object):     def __mul__(self, other):         pass      __rmul__ = __mul__ 
like image 131
kindall Avatar answered Nov 09 '22 00:11

kindall