Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

__add__

"""
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 :: torch tensor equal to 
Python :: how to get all distinct substrings in a string python 
Python :: python list insert 
Python :: list object attributes python 
Python :: position text in a box matplotlib 
Python :: add space before and after string python 
Python :: change index function for class python 
Python :: python get previous method name 
Python :: jupyter notebook not showing all null values 
Python :: python delete column 
Python :: reverse a number in python 
Python :: no of words in a string in python 
Python :: how to sort subset of rows in pandas df 
Python :: python typewriter effect 
Python :: webdriver.chrome() python not working 
Python :: python ordered indexs of a list 
Python :: Flask / Python. Get mimetype from uploaded file 
Python :: how to format a file in python 
Python :: append numeric number in and auto increment in using pandas 
Python :: python send email from icloud 
Python :: how to encode a string in python 
Python :: python grab results from cursor.execute 
Python :: Python Zigzag a matrix for dct 
Python :: getting last n rows of column 
Python :: python for loop float increment 
Python :: add python to zsh wsl 
Python :: pydub audiosegment to numpy array 
Python :: python linear search 
Python :: check whether number is even or odd 
Python :: import modules given the full path python 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =