Junior — Middle
What is the purpose of the __get__ method in Python?
sobes.tech AI
Answer from AI
In Python, the magic method __getattr__ is used to intercept access to non-existent attributes, while the __get__ method is part of the descriptor protocol that manages attribute access. However, the question mentions __get, which is characteristic of PHP, not Python.
If we talk about PHP, the magic method __get is called when attempting to access a non-existent or inaccessible (e.g., private) property of an object. This allows for dynamic handling of such accesses, for example, returning computed values or data from another source.
Example in PHP:
class User {
private $data = ['name' => 'Ivan', 'age' => 30];
public function __get($property) {
if (array_key_exists($property, $this->data)) {
return $this->data[$property];
}
return null;
}
}
$user = new User();
echo $user->name; // Outputs "Ivan"
Thus, __get allows implementing lazy loading of properties or controlling access to data.