Implicit conversions in Python

For example, if I wanted to apply mathematical operations on objects as follows:

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

     def __repr__(self):
         return value

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

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

Is it possible to evaluate objects for primitives so that I can apply simple operations to them? Similarly, as you could use implicit conversionsin Scala.

+4
source share
4 answers

You can implement __add__to define adding to 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 Ato other instances Ato get a third instance A. You can write __add__adaptable to the type of operands you need to work.

. __radd__ __iadd__.

+6

, . +, __add__:

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)

, , , , , __eq__:

   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

( , , , )

+2

, , , . Python , , , __add__() __radd__().

0

There is not enough context to know that foo should be equivalent to foo.value, so with the Python philosophy, explicit is better than implicit . You can, of course, be a subclass int, but then the operators will not create your new class, and the object itself will remain unchanged (as usual in Python). It is noteworthy that ctypes, such as c_int32, have a value attribute, for example your example, but do not use numeric operators.

0
source

Source: https://habr.com/ru/post/1617622/


All Articles