The abs()
function is one of Python's built-in functions that returns the absolute value of a number. This function takes a single parameter, which can be an integer, floating-point number, or complex number.
Example Code
x = -10
y = 20.5
z = -4 + 3j
print(abs(x)) # Output: 10
print(abs(y)) # Output: 20.5
print(abs(z)) # Output: 5.0 (absolute value of complex number)
If the parameter x
defines the __abs__()
method, then abs(x)
will return x.__abs__()
:
class stuff:
def __init__(self,char):
self.char = char
def __abs__(self):
return "[" + self.char + "]"
a = stuff("A")
print(abs(a)) # Output: [A]