Last active
February 14, 2019 02:36
-
-
Save atannus/b39b38a7b47ff9bc7e731bdd6b674b16 to your computer and use it in GitHub Desktop.
Python Operator Overload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" A simple example of overloading the plus operator. | |
Instances are created by passing a notation consisting of a numerical value followed by one of the supported | |
dimensions (m, cm, mm) separated by a single space. | |
Adding two values initialized with different dimensions returns an object with the dimension of the first value. | |
Example: | |
l1 = Length('1 mm') | |
l2 = Length('1 m') | |
print(l1 + l2) | |
# 1001.0 mm | |
print(l2 + l1) | |
# 1.001 m | |
""" | |
__author__ = "André Tannús" | |
__email__ = "[email protected]" | |
__license__ = "MIT" | |
__status__ = "Prototype" | |
class Length: | |
def __init__(self, notation): | |
self.supportedDimensions = {'m':1, 'cm':1e-2, 'mm':1e-3} | |
parts = notation.split(' ') | |
self.magnitude = float(parts[0]) | |
self.dimension = parts[1] | |
self.notation = notation; | |
def getFactor(self, fromDim, toDim): | |
return self.supportedDimensions[fromDim] / self.supportedDimensions[toDim]; | |
def __add__(self, operand): | |
newMagnitude = self.magnitude + (operand.magnitude * self.getFactor(operand.dimension, self.dimension)) | |
return Length(str(newMagnitude) + ' ' + self.dimension) | |
def __str__(self): | |
return self.notation; | |
l1 = Length('1 mm') | |
l2 = Length('1 m') | |
print(l1 + l2) | |
# 1001.0 mm | |
print(l2 + l1) | |
# 1.001 m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment