SoFunction
Updated on 2024-11-16

Deeper understanding of the use of common magic methods in Python virtual machines

This article introduces you to some common magic methods in python. This article is about some magic methods related to mathematical computation, which are used in many packages for scientific computation.

size comparison

When we define our own classes in Python, we can change the comparison behavior of objects by overriding some special methods. These special methods include__lt____le____eq____ne____gt__cap (a poem)__ge__, which correspond to the less-than, less-than-equal, equal-to, not-equal, greater-than, and greater-than-equal comparison operators. These methods allow us to customize the comparison rules between objects.

Below is a detailed description of each method:

  • object.__lt__(self, other) This method is used to define the behavior of the less-than (<) operator. This method is called when we compare two objects using the less than operator. If theselfObjects less thanotherobject, then it returns theTrueOtherwise, returnFalse
  • object.__le__(self, other) This method is used to define the behavior of the less-than-equal (<=) operator. This method is called when we compare two objects using the less than or equal to operator. If theselfObjects less than or equal tootherobject, then it returns theTrueOtherwise, returnFalse
  • object.__eq__(self, other) This method is used to define the behavior of the equal to (==) operator. This method is called when we compare two objects using the equal to operator. If theselfThe object is equal to theotherobject, then it returns theTrueOtherwise, returnFalse
  • object.__ne__(self, other) This method is used to define the behavior of the not-equal (! =) operator's behavior. This method is called when we compare two objects using the not equal operator. If theselfThe object is not equal to theotherobject, then it returns theTrueOtherwise, returnFalse
  • object.__gt__(self, other) This method is used to define the behavior of the greater than (>) operator. This method is called when we compare two objects using the greater than operator. If theselfObjects larger thanotherobject, then it returns theTrueOtherwise, returnFalse
  • object.__ge__(self, other) This method is used to define the behavior of the greater-than-equal (>=) operator. This method is called when we compare two objects using the greater than or equal to operator. If theselfObjects greater than or equal tootherobject, then it returns theTrueOtherwise, returnFalse

These comparison methods allow us to customize the comparison rules for objects according to our needs. When we compare objects using comparison operators, Python automatically calls these methods and returns the appropriate results.

Here is a simple example showing how to use these comparison methods in a custom class:

class Point:
    def __init__(self, x, y):
         = x
         = y
    
    def __lt__(self, other):
        return  <  and 
        return  < 
    
    def __le__(self, other):
        return  <=  and  <= 
    
    def __eq__(self, other):
        return  ==  and  == 
    
    def __ne__(self, other):
        return not self.__eq__(other)
    
    def __gt__(self, other):
        return  >  and  > 
    
    def __ge__(self, other):
        return  >=  and  >= 
 
 
p1 = Point(1, 2)
p2 = Point(3, 4)
 
 
print(p1 < p2)  
print(p1 <= p2)
print(p1 == p2)
print(p1 != p2)
print(p1 > p2)
print(p1 >= p2)

The output of the above code is shown below:

2
True
False
True
False
False

In the above example, we defined a file namedPointclass, which represents a point on a two-dimensional plane. We rewrite the__lt____le____eq____ne____gt__cap (a poem)__ge__method to define a comparison rule between points. According to our definition, if a point'sxCoordinates andycoordinates are both less than the corresponding coordinates of the other point, then we consider the former point to be less than the latter.

By creating twoPointobjects and compare them using the comparison operator, we can see that the comparison operator returns the expected result according to our definition.

Simulating the design of a mathematical type

When we define our own classes in Python, we can change the behavior of arithmetic operations on objects by overriding some special methods. These special methods include__add____sub____mul____matmul____truediv____floordiv____mod____divmod____pow____lshift____rshift____and____xor__cap (a poem)__or__They correspond to the operators of addition, subtraction, multiplication, matrix multiplication, true division, integer division, modulo operation, divmod function, power operation, left shift, right shift, per-position and, per-position different or and per-position or. These methods allow us to customize the rules of arithmetic operations between objects.

  • object.__add__(self, other) This method is used to define the behavior of the addition (+) operator. This method is called when we add two objects using the addition operator. It returns the result of adding two objects.
  • object.__sub__(self, other) This method is used to define the behavior of the subtraction (-) operator. This method is called when we subtract two objects using the subtraction operator. It returns the result of subtracting two objects.
  • object.__mul__(self, other) This method is used to define the behavior of the multiplication (*) operator. This method is called when we multiply two objects using the multiplication operator. It returns the result of multiplying two objects.
  • object.__matmul__(self, other) This method is used to define the behavior of the matrix multiplication (@) operator. This method is called when we perform matrix multiplication on two objects using the matrix multiplication operator. It returns the result of matrix multiplication of two objects.
  • object.__truediv__(self, other) This method is used to define the behavior of the true division (/) operator. This method is called when we divide two objects using the true division operator. It returns the result of dividing two objects.
  • object.__floordiv__(self, other) This method is used to define the behavior of the integer division (//) operator. This method is called when we divide and round two objects using the integer division operator. It returns the result of dividing and rounding two objects.
  • object.__mod__(self, other) This method is used to define the behavior of the modulo (%) operator. This method is called when we perform a modulo operation on two objects using the modulo operator. It returns the result of the modulo operation on the two objects.
  • object.__divmod__(self, other)This method is used to define the behavior of the divmod function. divmod function takes two arguments and returns a tuple containing the quotient and remainder. This method is called when we use the divmod function on two objects. It returns a tuple containing the quotient and remainder of the two objects.
  • object.__pow__(self, other[, modulo]) This method is used to define the behavior of the power (**) operator. This method is called when we perform a power operation on two objects using the power operator. It returns the result of the power operation on both the objects. Optional.moduloparameter is used to specify the modulus of the modulo operation.
  • object.__lshift__(self, other) This method is used to define the behavior of the left shift (<<) operator. This method is called when we use the left shift operator on an object. It returns the result after the object is shifted left by the specified number of bits.
  • object.__rshift__(self, other) This method is used to define the behavior of the right shift (>>) operator. This method is called when we use the right shift operator on an object. It returns the result after the object is shifted right by the specified number of bits.
  • object.__and__(self, other) This method is used to define the behavior of the press-and (&) operator. This method is invoked when we use the press-and-parallel operator on two objects. It returns the result of the two objects in terms of the bitwise sum.
  • object.__xor__(self, other) This method is used to define the behavior of the per-positional different-or (^) operator. This method is called when we use the per-positional different or operator on two objects. It returns the result of bitwise or of the two objects.
  • object.__or__(self, other) This method is used to define the behavior of the per-or (|) operator. This method is called when we use the bitwise or operator on two objects. It returns the result of the bitwise or of the two objects.

By overriding these methods, we can define rules for arithmetic operations between objects in our custom class. When we operate on an object using the appropriate arithmetic operator or function, Python will automatically call these methods and return the appropriate result.

Here is a simple example showing how to use these arithmetic methods in a custom class:

class Vector:
    def __init__(self, x, y):
         = x
         = y
 
    def __add__(self, other):
        return Vector( + ,  + )
 
    def __sub__(self, other):
        return Vector( - ,  - )
 
    def __mul__(self, scalar):
        return Vector( * scalar,  * scalar)
 
    def __truediv__(self, scalar):
        return Vector( / scalar,  / scalar)
 
    def __repr__(self):
        return f"Vector[{}, {}]"
 
 
# Create two Vector objects
v1 = Vector(1, 2)
v2 = Vector(3, 4)
 
# Operate with arithmetic operators
v3 = v1 + v2
v4 = v1 - v2
 
v5 = v1 * 2
v6 = v2 / 3
 
print(f"{v1 = }")
print(f"{v2 = }")
print(f"{v3 = }")
print(f"{v4 = }")
print(f"{v5 = }")
print(f"{v6 = }")

The output of the above code is shown below:

v1 = Vector[1, 2]
v2 = Vector[3, 4]
v3 = Vector[4, 6]
v4 = Vector[-2, -2]
v5 = Vector[2, 4]
v6 = Vector[1.0, 1.3333333333333333]

In the example above, we defined a file namedVectorclass, which represents two-dimensional vectors. We rewrite the__add____sub____mul__cap (a poem)__truediv__method to define rules for addition, subtraction, multiplication and true division between vectors. According to our definition, addition of vectors is adding the corresponding components, subtraction of vectors is subtracting the corresponding components, multiplication of vectors is multiplying each component by a scalar, and true division of vectors is dividing each component by a scalar. This is accomplished by creating twoVectorobject and operate with the arithmetic operator, we can see that the arithmetic operator returns the expected result according to our definition.

When we define our own classes in Python, in addition to overriding some magic methods to change the behavior of arithmetic operations on objects, we can also override the corresponding reverse magic methods to handle reverse operations. These reverse magic methods begin with__rfollowed by the corresponding operator, e.g.__radd____rsub____rmul__etc. They are used to try to use the current object's magic methods to handle reverse arithmetic when it is not possible to call the corresponding magic methods directly on another object. The main methods are the following:

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__imatmul__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)

For example, a + b, when a is not defined in__add__is called when b's__radd__ . Take for example the following example:

class A:
    def __init__(self, x):
         = x
class B:
    def __init__(self, x):
         = x
    def __radd__(self, other):
        print("In B __radd__")
        return  + 
if __name__ == '__main__':
    a = A(1)
    b = B(1)
    print(a + b)

The output of the above code is shown below:

In B __radd__
2

In addition to the above magic methods on data, there are some other magic methods as shown below:

object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)
object.__complex__(self)
object.__int__(self)
object.__float__(self)
object.__index__(self)
object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)
  • object.__neg__(self) This method is used to define the behavior of the minus (-) operator. When the minus operator is applied to an object, the object's__neg__method. It returns a new object representing the opposite of the current object.
  • object.__pos__(self) This method is used to define the behavior of the plus sign (+) operator. When the plus sign operator is applied to an object, the object's__pos__method. It returns a copy of the current object.
  • object.__abs__(self) This method is used to define the behavior of the absolute value (abs()) function. When applying theabs()function to an object calls the object's__abs__method. It returns the absolute value of the current object.
  • object.__invert__(self) This method is used to define the behavior of the inverse per bit (~) operator. When applying the inverse by bit operator to an object, the object's__invert__method. It returns the result of inverting the current object bitwise.
  • object.__complex__(self) This method is used to define thecomplex()Behavior of a function for converting objects to plural form. When applying thecomplex()function to an object calls the object's__complex__method. It returns a plural object representing the current object.
  • object.__int__(self) This method is used to define theint()Behavior of a function to convert an object to integer form. When applying theint()function to an object calls the object's__int__method. It returns an integer object representing the current object.
  • object.__float__(self) This method is used to define thefloat()Behavior of a function to convert an object to floating point form. When applying thefloat()function to an object calls the object's__float__method. It returns a floating point object representing the current object.
  • object.__index__(self) This method is used to define the()Behavior of a function to convert an object to an integer index. When applying the()function to an object calls the object's__index__method. It returns an integer object indicating that the current object can be used as an index.
  • object.__round__(self[, ndigits]) This method is used to define theround()Behavior of the function for rounding objects. When applying theround()function to an object calls the object's__round__method. Optionalndigitsparameter specifies the number of decimal places, the default is None. it returns a new object that represents the result of rounding the current object.
  • object.__trunc__(self) This method is used to define the()Behavior of a function to truncate an object to an integer. When applying the()function to an object calls the object's__trunc__Methods.

summarize

This post describes the use of magic methods in Python to change the behavior of comparison and arithmetic operations on objects. For comparison operators, this can be done by overriding the__lt____le____eq____ne____gt__cap (a poem)__ge__method to define rules for comparison between custom objects. For arithmetic operators, you can define custom comparison rules between objects by overriding the__add____sub____mul____matmul____truediv____floordiv____mod____divmod____pow____lshift____rshift____and____xor__cap (a poem)__or__methods to define rules for arithmetic operations between objects. These methods allow objects of custom classes to have similar behavior to built-in types.

This post also mentions the reverse magic method, which starts with a__rMethods that begin with the word for dealing with inverse arithmetic. For example, the__radd____rsub____rmul__and other methods can define the behavior of an object in a reverse operation.

With sample code, the article demonstrates how these magic methods can be overridden in a custom class to implement custom rules for comparison and arithmetic operations. Finally, the expected results obtained when using these methods in a custom class are shown.

In summary, by understanding and using these magic methods, we can better control the comparison and arithmetic behavior of custom class objects in Python to make them more responsive to specific needs.

To this point, this article on the use of common magic methods in the Python virtual machine in-depth understanding of the article is introduced to this, more related Python magic method content, please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!