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 :: reply_photo bot telegram python 
Python :: django changing boolean field from view 
Python :: class inside class python 
Python :: read xml file in python 
Python :: add elements to list python 
Python :: how to pop an exact number from a list in python 
Python :: convert int to string python 
Python :: how to get the number of rows and columns in a numpy array 
Python :: codechef solution 
Python :: print format python 
Python :: pandas bins dummy 
Python :: python dict if key does not exist 
Python :: get request in django 
Python :: discord.py events 
Python :: python time 
Python :: python create a set of class 
Python :: max function python 
Python :: embed variables python 
Python :: python use variable inside pandas query 
Python :: remove columns that start with pandas 
Python :: Access the Response Methods and Attributes in python Show HTTP header 
Python :: groupby fillna 
Python :: current page django 
Python :: pandas describe 
Python :: how to iterate set in python 
Python :: formatted string in python 
Python :: python __repr__ meaning 
Python :: Access the elements using the [] syntax nested dictionary 
Python :: how to use a for loop in python 
Python :: infinite monkey theorem 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =