Sobes.tech
Junior — Middle

Could you provide an example of using special methods that are called automatically in certain situations?

sobes.tech AI

Answer from AI

In Python, there are special methods (magic methods) that are called automatically in certain situations. For example:

  • __init__ — called when creating an object for initialization.
  • __str__ — called when converting an object to a string (e.g., when calling print).
  • __enter__ and __exit__ — used in context managers (with), automatically called when entering and exiting a block.

Example with a context manager:

class FileManager:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

with FileManager('example.txt') as f:
    data = f.read()
    print(data)

Here, __enter__ automatically opens the file, and __exit__ closes it, even if an error occurs inside the block.

Could you provide an example of using special methods… - sobes.tech