Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python __truediv__ magic method

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

class Test:
    def __init__(self, x):
        self.x = x
    
    def __truediv__(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 divide 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 divide these two objects.
print(t / t2)	# 2.5, without __truediv__ the object doesn't understand the "/" sign.

Comment

PREVIOUS NEXT
Code Example
Python :: Python how to use __ge__ 
Python :: Python __ne__ magic method 
Python :: django ejemplo de un formulario crud 
Python :: how to get defintiion of pysspark teable 
Python :: NumPy bitwise_and Example When inputs are arrays 
Python :: program adxl335 python 
Python :: how to split a string every 2 characters python 
Python :: sourcetrail index library python 
Python :: NumPy packbits Code Packed array along default axis 
Python :: django view - mixins and GenericAPIView (list or create - GET, POST) 
Python :: Termfastapi get ip 
Python :: lambda to redshift python 
Python :: Python PEP (class) 
Python :: Remove Brackets from List Using join method 
Python :: django hash password Argon 
Python :: from android.runnable in python 
Python :: python how to convert each word of each row to numeric value of a dataframe 
Python :: combobox write disable tkinter 
Python :: how to loop 10 times in python 
Python :: how to add start menu in python 
Python :: Redirecting an old URL to a new one with Flask micro-framework 
Python :: extracting code blocks from Markdown 
Python :: xchacha20 
Python :: ring PostgreSQL load the postgresqllib.ring library 
Python :: ring Type Hints Library user types 
Python :: how to write stuff in python 
Python :: set change order python 
Python :: operator in django query 
Python :: rounding with .2g gives strange results 
Python :: how to multiply integer value with float values in python 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =