Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Python __sub__ magic method

"""
Magic method __sub__ is called when a "-" is used on any object. 
Given example shows what I mean: print(some_object - other_object)
This may give error often, so that means given objects don't have __sub__ method
"""

class Test:
    def __init__(self, x):
        self.x = x
    
    def __sub__(self, other):
    	""" 
    	self represents the object that is first and other is object after
    	"-" sign. What I say here is that I expect to have attribute "x" 
    	in both objects and I will try to subtract them. This SHOULD BE
    	used for objects of the same type.
    	"""
    	return self.x - other.x

t = Test(5)
t2 = Test(2)	# Now I can use subtraction.
print(t - t2)	# 3, without __sub__ the object doesn't understand the "-" sign.
 
PREVIOUS NEXT
Tagged: #Python #magic #method
ADD COMMENT
Topic
Name
4+8 =