Reputation: 4640
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
.
Upvotes: 4
Views: 1654
Reputation: 15877
There isn't enough context to know that foo should be equivalent to foo.value, so with Python's philosophy explicit is better than implicit. You can certainly subclass int
, but then the operators won't produce your new class, and the object itself would remain immutable (as numbers in Python generally are). Notably, ctypes such as c_int32 have a value attribute like your example but do not implement numeric operators.
Upvotes: 0
Reputation: 59103
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__
.
Upvotes: 6
Reputation: 14360
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)
Upvotes: 2
Reputation: 798556
The problem is that there isn't enough context in the expression to decide what the objects should be converted to. Python has various methods that can be defined on an object that implement various operators, including the __add__()
and __radd__()
methods.
Upvotes: 0