+ 1
What's the operator for __abs__() ?
after it is defined in class
6 ответов
+ 4
abs().
class num:
def __init__(self, val):
self.val = val
def __abs__(self):
return 2*self.val
def __repr__(self):
return f'{self.val}'
n = num(5)
print(abs(n))
#output: 10
+ 7
abs is absolute operator for numbers. It removes negative sign from a number (if it is negative). abs(-5)=5, abs(7)=7. __abs__ is the operator you can define for a class representing something numeric. So, you can use python function abs on the class. Example:
https://code.sololearn.com/c3V7yQ1kaldq/?ref=app
+ 2
I don't think there's an operator for abs() like +-/* etc. In mathematics you would use |num|, in python it's abs(num).
Double underscore methods like __abs__() allow you to define what your class does as soon as a standard function like abs(class) is called.
The most basic example is __add__(). It is called every time when two objects are added (using the syntax object + object). It might look weird, but because everything is an object in python (even a number), instead of print(5+6) you can also write print((5).__add__(6)) and get the same result.
Maybe that doesn't really answer your question, but it is interesting to see how these double underscore methods work.
+ 2
In this case, you're very welcome 😀
+ 1
Thanks
My question should actually be
i) Is there a +-×÷ alike for abs?
ans: no
ii) Then, what is the difference between abs() and __abs__()?
ans: i found out already: account.abs() vs abs(account)
Also, return value not must int, can string, I experimented:
https://code.sololearn.com/cphJB40liGky/?ref=app
+ 1
It definitely does answer my question, (5).__add__(6) is something I didn't know, thanks.