Search
 
SCRIPT & CODE EXAMPLE
 

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

PREVIOUS NEXT
Code Example
Python :: __truediv__ 
Python :: Python how to use __ge__ 
Python :: python interpreter after running a python file 
Python :: palindrome rearrange 
Python :: NumPy rot90 Example Rotating Once 
Python :: using Canvas with tkinger 
Python :: 16. count total numbers of uppercase and lowercase characters in input string python 
Python :: scipy kullbach leibler divergence 
Python :: NumPy right_shift Syntax 
Python :: python subprocess redirect a file 
Python :: save axis and insert later 
Python :: # remove sensitive information like name, email, phone no from text 
Python :: adjoint of 3x3 matrix in numpy 
Python :: python truncade number 
Python :: python call c function 
Python :: lsit to dataframe 
Python :: pandas dataframe select columns multiple cell value 
Python :: function multiply(a b) 
Python :: changing labels of facetgrid 
Python :: Python batch file rename 
Python :: how to map url with usernames prefixed 
Python :: penis command discord.py 
Python :: patterns and matcher nfa python code 
Python :: ring print part of the content of a binary file 
Python :: how to deploy django app on heroku with mongodb 
Python :: install open3d jetson nano aarch64 
Python :: Use of OfficeApi 
Python :: python strip txt 
Python :: remove inner list from outer list python 
Python :: tuple merging 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =