14-3. Operator Polymorphism

Operator Polymorphism

  • Operator polymorphism means that the same operator can behave differently depending on the type of operands.
  • In Python, operators like +, *, ==, etc., are overloaded by default for various data types.

 

Built-in Operator Polymorphism

  • The meaning of an operator depends on the data types involved.

  • Although the operator is the same (+), it performs different operations:
    • Numeric addition for numbers
    • Concatenation for strings and lists
  • Comparison Operators
    • Operators like ==, !=, <, > also behave differently based on data types.

 

Custom Operator Polymorphism (Operator Overloading)

  • You can define or change the behavior of operators for user-defined classes by overriding special methods.

Example: Custom + Operator with Classes

  • Here, the + operator is polymorphic because it works for integers, floats, strings, lists, and even custom objects like Book.

 

Example: Overloading Comparison Operators

  • The > operator works here because we defined __gt__.