Syntax
object.__abs__()
Python’s object.__abs__()
method returns the absolute value of the object
and implements the built-in function abs()
.
The absolute value of any numerical input argument -x
or +x
is the corresponding positive value +x
. However, you can overwrite the default behavior by defining a custom __abs__()
method.
We call this a “Dunder Method” for “Double Underscore Method”. To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
Example
In the following example, you create a custom class Data
and overwrite the __abs__()
method so that it multiplies the attribute self.value
with 10.
class Data: def __init__(self, value): self.value = value def __abs__(self): return self.value * 10 my_value = Data(4.2) print(abs(my_value)) # 42.0
If you hadn’t defined the __abs__()
method, Python would’ve raised a TypeError
.
How to Resolve TypeError: bad operand type for abs(): ‘Data’
Consider the following code snippet where you try to call the built-in function abs()
on a custom object:
class Data: def __init__(self, value): self.value = value my_value = Data(4.2) print(abs(my_value))
Running this leads to the following error message on my computer:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 8, in <module> print(abs(my_value)) TypeError: bad operand type for abs(): 'Data'
The reason for this error is that the __abs__()
dunder method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: bad operand type for abs()
, you need to provide the __abs__(self)
method in your class definition as shown previously:
class Data: def __init__(self, value): self.value = value def __abs__(self): return self.value * 10 my_value = Data(4.2) print(abs(my_value)) # 42.0