Python Tutorial Python Advanced Python References Python Libraries

Python - Unary Operator Overloading



Unary operators are those operators which acts upon a single operand to produce a new value. Following is the list of unary operators and corresponding magic methods that can be overloaded in Python.

OperatorMagic Method
+__pos__(self)
-__neg__(self)
~__invert__(self)

The unary operators is used with object in the same way as it is used normally. The operator normally precedes object in the expression like - +obj, -obj, and ~obj.

Example: overloading unary minus (-) operator

In the example below, unary minus operator is overloaded. When it is used with vector object, it applies negation on x and y component of the object, for example - applying negation on (10, 15) will produce (-10, -15) and applying negation on (5, -25) will produce (-5, 25).

class vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __str__(self):
    return "({0},{1})".format(self.x, self.y)
  
  #function for operator overloading
  def __neg__(self):
    X = -self.x
    Y = -self.y
    return vector(X, Y)

#creating vector objects
v1 = vector(10, 15)
v2 = vector(5, -25)

#using overloaded unary - operator 
#with vector objects
v1 = -v1
v2 = -v2

#displaying the result
print("v1 =", v1)
print("v2 =", v2)

The output of the above code will be:

v1 = (-10,-15)
v2 = (-5,25)

❮ Python - Operator Overloading