Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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 :: python create list of empty lists 
Python :: py random.sample 
Python :: python defaultdict default value 
Python :: spacy import doc 
Python :: NumPy fliplr Syntax 
Python :: access key through value python 
Python :: python custom class indexing 
Python :: how to pick the latest data entered django 
Python :: check even or odd in single line 
Python :: Python Deleting a Tuple 
Python :: reverse a string or number in python 
Python :: migrate database in django 
Python :: python display text in label on new line 
Python :: get object by name blender python 
Python :: can i call a python script from a function 
Python :: noob python 
Python :: flask get request port 
Python :: how to skip number in while loop python 
Python :: wails install 
Python :: python sort list by rule 
Python :: array slicing python 
Python :: get all ForeignKey data by nesting in django 
Python :: algebraic pyramid python 
Python :: fastest way to compute pair wise distances python 
Python :: reverse relationship in django for one to one field for usage in Django rest serializer 
Python :: global /tmp/pip-req-build-civioau0/opencv/modules/videoio/src/cap_v4l.cpp (587) autosetup_capture_mode_v4l2 videoio(v4l2:/dev/video0): device is busy 
Python :: pytorch torchaudio torchvision cu113 
Python :: with open python print file name 
Python :: if statement python 
Python :: us states and capitals dictionary 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =