Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python how to use __sub__

"""
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.
Comment

PREVIOUS NEXT
Code Example
Python :: Python __ge__ 
Python :: Python how to use __sub__ 
Python :: Python how to use __truediv__ 
Python :: Python how to use __ne__ 
Python :: python model feature importance 
Python :: NumPy rot90 Example Rotating four times 
Python :: program adxl335 python 
Python :: godot knockback 
Python :: NumPy bitwise_or Code When inputs are numbers 
Python :: NumPy binary_repr Syntax 
Python :: make a dict from td scrape 
Python :: selenium python select elements data atribute 
Python :: python mysqldb sockets 
Python :: Python pattern of 1010101 
Python :: LCS Problem Python 
Python :: make dialog in the front by Pywinauto 
Python :: city of stars how many words in a song python code 
Python :: store dataframes 
Python :: python re return index of match 
Python :: Permission error 
Python :: Hide div element using python in Flask 
Python :: Filling a missing value in a pandas data frame with an if statement based on a condition 
Python :: linkedin bot python 
Python :: ring Copy Lists 
Python :: ring Load Syntax Files 
Python :: How to Load Any HuggingFace Model in spaCy 
Python :: how to store file into folder bucket aws 
Python :: consider a string note: "welcome" statment will rais error 
Python :: separate array along axis 
Python :: run django using nssm 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =