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 :: difference between == and is 
Python :: how to add to beginning of linked list python 
Python :: keras embedding 
Python :: dict to list python 
Python :: drf serializer unique together 
Python :: how i get url value in get_queryset function in drf 
Python :: python manually trigger exception 
Python :: python selenium element not interactable while headless 
Python :: how to create a numpy array linspace in python 
Python :: sorted set in python 
Python :: round to the nearest 0.5 
Python :: The function to be built, amino_acids, must return a list of a tuple and an integer when given a string of mRNA code. 
Python :: read excel by row and output to txt 
Python :: signup class 
Python :: python listas por comprension 
Python :: python read file between two strings 
Python :: python get global variable by name 
Python :: dbscan example 
Python :: programmer tool 
Python :: plt grid linestyles options 
Python :: python plot n numbers from normal distribution 
Python :: enum python print all options 
Python :: 2 functions at a time py 
Python :: How to take multiple inputs in one line in python using list comprehension 
Python :: Using replace() method to remove newlines from a string 
Python :: convert to string in python 
Python :: how to pass primary key to url django 
Python :: python casting float to int 
Python :: how to use custom activity in discord.py 
Python :: state capitals python 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =