Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
✞ ☎
class Point2D :
...
    def __mul__ ( self , other ):
        if isinstance ( other , Point2D ): # scalar product
             return self .x * other .x + self .y * other .y
        elif isinstance ( other , numbers . Number ): # scalar multiplication
             return Point2D ( other * self .x , other * self .y )
        else :
             return NotImplemented

    def __rmul__ ( self , other ):
       if isinstance ( other , numbers . Number ):
           return Point2D ( other * self .x , other * self .y )
       else :
           return NotImplemented

>>> p1 = Point2D(1,0)
>>> p1.x, p1.y
(1, 0)
>>> p2 = p1 * 42 # multiply p1 with a number
>>> p2.x, p2.y # yields a point
(42, 0)
>>> w = p1 * p2 # multiply two points
>>> w # yields a number
42
>>> p3 = 3 * p1 # multiply a number with a point
>>> p3.x, p3.y # yields a point
(3, 0)


What I have tried:

__mul__ and __rmul__,...............................
Posted
Updated 16-Jul-20 21:31pm
v3
Comments
Patrice T 16-Jul-20 17:53pm    
Ever think to read documentation ?

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900