Junior — Middle
Can you list and describe the magic methods used in object-oriented programming?
sobes.tech AI
Answer from AI
Magic methods are special methods in object-oriented programming that are automatically called in certain situations. They may have different names in various languages, but common examples include:
- Constructor — called when creating an object, initializes it.
- Destructor — called when destroying an object (e.g., in C++).
- String conversion method (e.g.,
__toString()in PHP,toString()in Java) — returns a string representation of the object. - Operator overloads (e.g., in Python
__add__,__eq__) — define the behavior of operators for objects. - Property access methods (e.g.,
__get,__setin PHP) — called when reading or writing properties.
Example in Python:
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value {self.value}"
def __add__(self, other):
return MyClass(self.value + other.value)
Here, __init__ is the constructor, __str__ is the string representation, and __add__ is the operator overload for addition.