Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries

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

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 below example, 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)

v1 = Vector(10, 15)
v2 = Vector(5, -25)
v1 = -v1
v2 = -v2
print("v1 =", v1)
print("v2 =", v2)

The output of the above code will be:

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

❮ Python - Operator Overloading