Junior — Middle
Can you explain the concept of magic methods in programming languages?
sobes.tech AI
Answer from AI
Magic methods are special methods in object-oriented programming languages (such as Python or PHP) that are automatically invoked in certain situations. They allow overriding the behavior of objects when performing standard operations such as creation, deletion, string conversion, arithmetic operations, and others.
For example, in Python, the magic method __init__ is called when creating an object, and __str__ is called when converting an object to a string:
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
p = Person("Ivan")
print(p) # Outputs: Person: Ivan
Thus, magic methods allow flexible control over object behavior without the need to explicitly call these methods.