| |||||||||||
| |||||||||||
Overloading operators in Python
![]()
In the Python language, you can define how operators work on different types of objects
that you create if you wish to do so. A far fetched capability? Not at all - if you add
numbers, you get the sum. If you add strings, you get them concatanated together. If you
add lists of tuples, you get a new list of tuple that's got all the elements of both. On
our training courses, one of the practicals we set is in adding cuboid objects together -
with the new enclosing volume being the greater of the incoming lengths, the greater of
the incoming breadths, and the sum of the incoming heights. Perhaps you'll have to think
about the logic behind that, but once you know that it works it will be encapsulated
(hidden within) the + operator and you'll be able to re-use it quickly and easily. On a recent Python course, I wrote a class demo to add animals together. If I added two male or two female animlals, not much happened. Add one animal of each gender, and a whole list of extra animals was constructed and returned. Show a large image More about intermediate objects in Python Associated topic - Python - Objects - Intermediate | |||||||||||
PH: 0800 043 8225 or 01225 708225 • FAX: 0845 8382 405 or 01225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho | |||||||||||