Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python __mul__ magic method

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

class Test:
    def __init__(self, x):
        self.x = x
    
    def __mul__(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 multiply 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 multiply these two objects together.
print(t * t2)	# 10, without __mul__ the object doesn't understand the "*" sign.
Comment

PREVIOUS NEXT
Code Example
Python :: remove stopwords from a sentence 
Python :: db connection string timeout 
Python :: array with zeros python 
Python :: raw string python 
Python :: pandas aggregate dataframe 
Python :: moving element to last position in a list python 
Python :: python unpacking 
Python :: print all variables jupyter notebook 
Python :: Sum of Product 1 
Python :: sns.heatmap 
Python :: change order of barh matplotlib 
Python :: how to get only one column from dataset in python 
Python :: Iterating Through Dictionaries with For Loops 
Python :: join two querysets django 
Python :: django models 
Python :: Append a line to a text file using the write() function 
Python :: how to take a list as input in python using sys.srgv 
Python :: how to round to 3 significant figures in python 
Python :: validate longitude and latitude in python 
Python :: args and kwargs 
Python :: instance method in python 
Python :: mongoengine 
Python :: python library to convert decimal into octal and hexadecimal 
Python :: __repr__ in python 
Python :: onedrive python upload 
Python :: how to create a string in python 
Python :: text color python tkinter 
Python :: python list merger 
Python :: firebase functions python 
Python :: remove toggle/pandaslux 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =