+ 2
Please explain to me in simple terms about magic method & object oriented products. Quiet confused now.
3 ответов
+ 4
You probably know that you can use + with type int.
5 + 3 == 8
You probably also know that you can use + with type str as well.
'5' + '3' == '53'
Different types make different use of operators or builtin functions, and 'magic methods' are special methods that define just that: The behavior of builtin python syntax for your custom-made types.
+ 1
Thanks Honfu. Very helpful explanation
0
Magic methods are built-in function you can override.
For instance :
class A:
def __init__(self, nb) :
self.n = nb
def __add__(self, Aobj):
return self.n + Aobj.n
A1 = A(4)
A2 = A(6)
print(A1 + A2)
#outputs 10
__init__ function, like __add__ or __str__ or __getattr__ or __setattr__ are magic methods.