Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversions in Python

Tags:

python

For example, if I wanted to apply mathematical operations on objects in the following way:

class A(object):
     def __init__(self, value):
         self.value = value

     def __repr__(self):
         return value

assert(A(1) + A(2) == 3)

I am getting the following error: TypeError: unsupported operand type(s) for +: 'A' and 'A'

Is it possible to evaluate objects to primitives so that I can apply simple operations on them? Similarly how you could use implicit conversions in Scala.

like image 846
Arturs Vancans Avatar asked Feb 09 '23 11:02

Arturs Vancans


2 Answers

You can implement __add__ to define addition on your class.

class A(object):
    def __init__(self, value):
       self.value = value
    def __repr__(self):
       return 'A(%r)'%self.value
    def __add__(self, other):
       return A(self.value+other.value)

>>> A(1)+A(2)
A(3)

This implementation assumes that you are only trying to add instances of A to other instances of A to get a third instance of A. You can write an __add__ adaptable to what type of operand you need it to work for.

See also __radd__ and __iadd__.

like image 132
khelwood Avatar answered Feb 12 '23 10:02

khelwood


That depends on what you're trying to do. You can define the + operator by defining the __add__ method:

class A(object):
   def __init__(self, value):
       self.value = value

   def __repr__(self):
       return value

   def __add__(self, other):
       return A(self.value + other.value)

then of course in your example code you're trying to compare it to an integer which also need to be defined - which is done by implementing the __eq__ method:

   def __eq__(self, other):
       try:
          self.value == other.value
       except AttributeError: # other wasn't of class A, try to compare directly instead 
          return self.value == other

(implicit typecasts on the other hand is not available as far as I know)

like image 37
skyking Avatar answered Feb 12 '23 11:02

skyking