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
Related Video

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.