Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python __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 how to use __div__ 
Python :: Python __ge__ magic method 
Python :: Python how to use __ne__ 
Python :: how to fetch limited rows in pandas dataframe using sqlalchemy 
Python :: NumPy rot90 Syntax 
Python :: p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass) 
Python :: funcs_and_args for loop python 
Python :: check if string is palindrome using recursion in python 
Python :: Snippet for inverse a matrix using numpy 
Python :: lambda function in python to shut ec2 at the time zone 
Python :: main code for bpsk scheme 
Python :: # find all text files in directory or any type of files in directory 
Python :: adjugate of 3x3 matrix in python 
Python :: Use PIP from inside script 
Python :: how to do alignment of fasta in biopython 
Python :: cv2 recize 
Python :: comprehension 
Python :: fetch inbox mail python 
Python :: installing blacksheep 
Python :: python list len 
Python :: Wtforms: How to generate blank value using select fields with dynamic choice values 
Python :: Python 3 (python 3.7.3) sample 
Python :: python for loop skip iteration if condition not met jinja 
Python :: ring get the type a given path (file or directory) 
Python :: list duplicate files between two folders python 
Python :: python adx indicator 
Python :: OfficeApi 
Python :: global variable not accessible withing thread 
Python :: trello class 
Python :: creating a news app using djangio 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =