+ 2

Please explain to me in simple terms about magic method & object oriented products. Quiet confused now.

Python

20th Mar 2019, 8:06 PM
Wanangwah
Wanangwah - avatar
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.
21st Mar 2019, 12:12 AM
HonFu
HonFu - avatar
+ 1
Thanks Honfu. Very helpful explanation
21st Mar 2019, 6:45 AM
Wanangwah
Wanangwah - avatar
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.
20th Mar 2019, 9:54 PM
Théophile
Théophile - avatar