In Python, you can get the absolute value of number by using the abs()
method. It can be used with the following:
Integer Absolute Value
You can get an integer in absolute form in the following way:
print(abs(1234)) #=> 1234 print(abs(-1234)) #=> 1234
Floating Point Absolute Value
You can pass a floating point number to the abs()
method, for example, like so:
print(abs(12.34)) #=> 12.34 print(abs(-12.34)) #=> 12.34
Complex Number Absolute Value
You can use the abs()
method with a complex number, which would return its magnitude:
# complex numbers print(abs(1234j)) #=> 1234.0 print(abs(-1234j)) #=> 1234.0
Object Absolute Value
If an object implements the __abs__()
method, then can pass it to the abs()
method.
For example, you could create a "NumericStr
" class that accepts numeric strings as value. You can define how these values are converted to their absolute form by implementing the __abs__()
method, like so:
class NumericStr: def __init__(self, value): self.value = value def __abs__(self): return self.value.replace('-', '') num1 = NumericStr('1234') num2 = NumericStr('-1234') print(abs(num1)) #=> '1234' print(abs(num2)) #=> '1234'
Without such an implementation, using a numeric string with the abs()
method would not possible as it only accepts numbers:
# TypeError: bad operand type for abs(): 'str'
print(abs('-1234'))
If the object does not implement the __abs__()
method, and you pass it to the abs()
method, then it will raise an error:
class NumericStr:
def __init__(self, value):
self.value = value
# TypeError: bad operand type for abs(): 'NumericStr'
print(abs(NumericStr('1234')))
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.