Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python __mul__

"""
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 :: Python Changing a Tuple 
Python :: python print values inside request.POST 
Python :: session in django 
Python :: is python a scripting language 
Python :: python float range 
Python :: how to set the size of a kivy window bigger than screen 
Python :: dict to string 
Python :: spacy get number of tokens 
Python :: sum of product 1 codechef solution 
Python :: python does string contain space 
Python :: python array find lambda 
Python :: how to generate list in python 
Python :: python outlook 
Python :: python hash and unhash string 
Python :: python decision tree classifier 
Python :: how to calculate approximate distance with latitude and longitude 
Python :: call matlab function from python 
Python :: django.db.utils.IntegrityError: 
Python :: Python Regex Backslash “” 
Python :: adding strings together in python 
Python :: pandas dataframe convert yes no to 0 1 
Python :: remove all parentheses from string python 
Python :: Python Read the CSV file 
Python :: datetime to unix timestamp python 
Python :: Math Module exp() Function in python 
Python :: python online practice test 
Python :: tkinter hide widget 
Python :: python local variables 
Python :: steps in for loop python 
Python :: analog of join in pathlibn 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =