Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python __add__ magic method

"""
Magic method __add__ 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 __add__ method
"""

class Test:
    def __init__(self, x):
        self.x = x
    
    def __add__(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 add them together. This SHOULD BE
    	used for objects of the same type.
    	"""
    	return self.x + other.x

t = Test(5)
t2 = Test(2)	# Now I can add these two objects together.
print(t + t2)	# 7, without __add__ the object doesn't understand the "+" sign.
Comment

PREVIOUS NEXT
Code Example
Python :: class python __call__ 
Python :: iterate rows and columns dataframe 
Python :: how to change theme of jupyter notebook 
Python :: telegram bot documentation python 
Python :: python text recognition 
Python :: mechanize python #3 
Python :: List get both index and value. 
Python :: To convert Date dtypes from Object to ns,UTC with Pandas 
Python :: validate string using six library python 
Python :: how to send image to template thats not in static flask 
Python :: even in python 
Python :: django migrate 
Python :: subprocess the system cannot find the file specifie 
Python :: python chunk text 
Python :: fillna pandas inplace 
Python :: copy along additional dimension numpy 
Python :: python global lists 
Python :: how to call a class from another class python? 
Python :: software developer tools list 
Python :: how to input sentence in python 
Python :: sum() python 
Python :: Exiting from python Command Line 
Python :: Merge 2 or more notebooks into one 
Python :: channel unhiding command in discord.py 
Python :: check pd.NaT python 
Python :: re sub python 
Python :: Finding Maximum Elements along columns using Python numpy.argmax() 
Python :: plot multiple columns in different colors plotly 
Python :: numpy if zero is present 
Python :: us staes python 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =