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
.
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__
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With