Home python Operator Overloading python

Operator Overloading python




I can not understand what operator overloading, read in Google, but do not throw stones razobralsya.Ne that I went on google and ask vas.Prosto from person-to-person information can be quickly understood than swipe a bunch oxbow google. If someone thought up to explain, let’s take a small example that will be useful in practice, please:)

Answer 1, Authority 100%

Overloading – is an indication of what actions will be carried out in the application, for example, arithmetic operators to objects of your class. For example, what will happen if you try to add two objects. It is not always necessary, but it is often useful.

For example, in Java there is no operator overloading, so with essentially numeric type BigDecimal has to work not by arithmetic operators (+ , - , / , * ), and using the methods (add , subtract , divide , multiply ):

BigDecimal sum = BigDecimal.ZERO;
for (Instrument instrument: cart.getInstruments ()) {
  sum = sum.add (instrument.getPriceForDay ());
sum = sum.multiply (BigDecimal.valueOf (cart.getDays ()));

The same code in Python with the type Decimal :

summa = Decimal (0)
for instrument in cart.instruments:
  summa + = instrument.price_for_day # + = operator is overloaded
summa * = cart.days # operator = overloaded

In this case, in the example of Python code readability is much better. But zlouptreblyat overload and should not – do not need to do overload just like that, “was to”


A synthetic example of operator overloading: there is a “rope” class. At the rope is only one feature – length. Rope we can extend (tie another rope, the lengths of at lengthening assembly for simplicity not included).

class Rope:
  def __init __ (self, length):
    self._length = length
  def __len __ (self):
    # Override operator len
    return self._length
  def __add __ (self, other):
    # Override operator +
    if isinstance (other, self .__ class__):
      # If the second object (ie what folding) of the same class
      return Rope (self._length + other._length) # returns a new object
    elif isinstance (other, (int, float)):
      # If the second object - a number
      return Rope (self._length + other) # returns a new object
      raise TypeError
  def __iadd __ (self, other):
    # Override operator + =
    if isinstance (other, self .__ class__):
      # If the second object of the same class
      self._length + = other._length # Modifies an existing object
      return self
    elif isinstance (other, (int, float)):
      # If the second object - a number
      self._length + = other # Modifies an existing object
      return self
      raise TypeError
rope = Rope (10) the new rope length # 10
rope1 = rope + # 10 or rope1 = rope + Rope (10)
print (len (rope)) # Output: 10 (original rope length is not changed)
print (len (rope1)) # Output: 20
rope + = 12 # or rope1 + = Rope (12)
print (len (rope)) # Output: 22
rope + = 'rope' # TypeError

Answer 2, Authority 100%

Reboot operators – a description of the logic for the cases of non-standard use of operators, for example, for user objects


For example, a value area:

class Square ():
  def __init __ (self, length, depth):
    self.length = length
    self.depth = depth
    self.square = self.length * self.depth

And there is the object height:

class Height:
  def __init __ (self, height):
    self.height = height

To obtain volume, you need to multiply the area to the height. If the “motor” multiply, then we get a mistake:

s = square ()
H = Height ()
V = S * H


Typeerror: Unsupported Operand Type (s) for *: 'Square' and 'Height'

Here it will help to restart the multiplication operator.
Restart syntax Look for yourself.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions