There is nothing wrong with the accepted answer to this question, but I am adding a few quick snippets to illustrate how this can be used. (Note that you can also βoverloadβ several types of processing methods.)
"""Return the difference of another Transaction object, or another class object that also has the `val` property.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return self.val - other.val buy = Transaction(10.00) sell = Transaction(7.00) print(buy - sell)
"""Return a Transaction object with `val` as the difference of this Transaction.val property and another object with a `val` property.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return Transaction(self.val - other.val) buy = Transaction(20.00) sell = Transaction(5.00) result = buy - sell print(result.val)
"""Return difference of this Transaction.val property and an integer.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return self.val - other buy = Transaction(8.00) print(buy - 6.00)
binarysubstrate
source share