Search
 
SCRIPT & CODE EXAMPLE
 

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 __div__ magic method 
Python :: __ge__ 
Python :: Python __ne__ magic method 
Python :: modles en django 
Python :: NumPy fliplr Example 
Python :: function nbYear(p0, percent, aug, p) { let n = 0; while(p0 < p) { p0 = p0 + Math.round(p0 * (percent/100)) + aug; n ++; } return n; } 
Python :: how to run string like normal code in python 
Python :: python string josin 
Python :: NumPy invert Code When inputs are Boolean 
Python :: pymenu example 
Python :: data base creation 
Python :: #check if the given date is a weekday or weekend 
Python :: dictionary display 
Python :: how to avoind DeprecationWarning in python 
Python :: create loop python 
Python :: parameter name in string 
Python :: list[:] 
Python :: create multiple marks python for python 
Python :: python relative seek 
Python :: lxml etree fromstring find 
Python :: docstring python pycharm 
Python :: Python (cpython 2.7.16) sample 
Python :: self.stdout.write django 
Python :: ring open another file 
Python :: list duplicates of specific file in folder python 
Python :: equivalent of geom smooth function in python using plotline lib 
Python :: 0 
Python :: sympy.diff 
Python :: payphone lyrics 
Python :: Quiver Simple Demo 
ADD CONTENT
Topic
Content
Source link
Name
4+1 =