Python practice · 15 questions

Python OOP and advanced topics: practice set

15 questions on object-oriented Python as interviews test it: encapsulation, overriding, dunder methods, class design, context managers and generator pipelines. Every "what does this print" answer was checked by running the code. At the end you get a score per topic.

  1. Question 1 of 15 · EncapsulationWhat does this print?
    Python
    class Account:
        def __init__(self):
            self.__balance = 100
    
    a = Account()
    print(hasattr(a, '__balance'), a._Account__balance)
  2. Question 2 of 15 · EncapsulationWhat does this print?
    Python
    class Temperature:
        def __init__(self, c):
            self.celsius = c
    
        @property
        def celsius(self):
            return self._c
    
        @celsius.setter
        def celsius(self, value):
            if value < -273.15:
                raise ValueError('below absolute zero')
            self._c = value
    
    try:
        t = Temperature(-300)
        print('created')
    except ValueError as e:
        print('rejected:', e)
  3. Question 3 of 15 · EncapsulationWhat does this print?
    Python
    class Job:
        def __init__(self):
            self._retries = 3
    
    job = Job()
    job._retries = 10
    print(job._retries)
  4. Question 4 of 15 · Inheritance & overridingWhat does this print?
    Python
    class Loader:
        def run(self):
            return f'{self.extract()} -> load'
    
        def extract(self):
            return 'base extract'
    
    class S3Loader(Loader):
        def extract(self):
            return 's3 extract'
    
    print(S3Loader().run())
  5. Question 5 of 15 · Inheritance & overridingWhat does this print?
    Python
    class Base:
        def __init__(self):
            self.name = 'base'
    
    class Child(Base):
        def __init__(self):
            self.size = 1
    
    c = Child()
    print(hasattr(c, 'name'), c.size)
  6. Question 6 of 15 · Inheritance & overridingWhat does this print?
    Python
    class Calc:
        def add(self, a, b):
            return a + b
    
        def add(self, a, b, c):
            return a + b + c
    
    try:
        print(Calc().add(1, 2))
    except TypeError:
        print('TypeError')
  7. Question 7 of 15 · Inheritance & overridingWhat does this print?
    Python
    print(isinstance(True, int), issubclass(bool, int), True + True)
  8. Question 8 of 15 · Dunder methodsWhat does this print?
    Python
    class Point:
        def __init__(self, x):
            self.x = x
    
        def __eq__(self, other):
            return self.x == other.x
    
    try:
        print(len({Point(1), Point(1)}))
    except TypeError:
        print('TypeError')
  9. Question 9 of 15 · Dunder methodsWhat does this print?
    Python
    class Table:
        def __repr__(self):
            return 'Table(orders)'
    
    print(str(Table()), [Table()])
  10. Question 10 of 15 · Dunder methodsWhat does this print?
    Python
    class Batch:
        def __init__(self, rows):
            self.rows = rows
    
        def __len__(self):
            return len(self.rows)
    
    print(bool(Batch([])), bool(Batch([1, 2])))
  11. Question 11 of 15 · Dunder methodsWhat does this print?
    Python
    class Money:
        def __init__(self, v):
            self.v = v
    
        def __add__(self, other):
            return Money(self.v + other.v)
    
    try:
        print(sum([Money(1), Money(2)]).v)
    except TypeError:
        print('TypeError')
  12. Question 12 of 15 · Class designWhat does this print?
    Python
    class Config:
        def __init__(self, env):
            self.env = env
    
        @classmethod
        def from_dict(cls, d):
            return cls(d['env'])
    
    class ProdConfig(Config):
        pass
    
    print(type(ProdConfig.from_dict({'env': 'prod'})).__name__)
  13. Question 13 of 15 · Class designWhat does this print?
    Python
    class Row:
        __slots__ = ('id', 'value')
    
        def __init__(self, id, value):
            self.id, self.value = id, value
    
    r = Row(1, 'a')
    try:
        r.extra = True
        print('added')
    except AttributeError:
        print('AttributeError')
  14. Question 14 of 15 · Context managers & generatorsWhat does this print?
    Python
    class Suppress:
        def __enter__(self):
            return self
    
        def __exit__(self, exc_type, exc, tb):
            print('exit', exc_type.__name__, end=' ')
            return True
    
    with Suppress():
        1 / 0
    print('after')
  15. Question 15 of 15 · Context managers & generatorsWhat does this print?
    Python
    def read():
        for i in range(3):
            print('read', i, end='; ')
            yield i
    
    def double(rows):
        for r in rows:
            print('double', r, end='; ')
            yield r * 2
    
    for x in double(read()):
        pass
0 of 15 answered

Revise the topics in the Python guide and Python for Data Engineers guide.