OOP Internals — Series 2

Preview — 3 of 10 questions

What is the output of the following code?

javascript
class Plugin:
    def __init_subclass__(cls, category=None, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.category = category

class Exporter(Plugin, category="export"):
    pass

class Importer(Plugin, category="import"):
    pass

print(Exporter.category)
print(Importer.category)
ANone, None — keyword arguments in a class definition are only usable by a custom metaclass, never by __init_subclass__.
Bexport, import
CTypeError: __init_subclass__() got an unexpected keyword argument 'category'
Dexport, export — category is bound once on Plugin itself and shared by every subclass.

What is the output of the following code?

javascript
class MetaA(type):
    def greet(cls):
        return "A"

class MetaB(type):
    def greet(cls):
        return "B"

class MetaAB(MetaA, MetaB):
    pass

class Base1(metaclass=MetaA):
    pass

class Base2(metaclass=MetaB):
    pass

class Combined(Base1, Base2, metaclass=MetaAB):
    pass

print(Combined.greet())
print(type(Combined).__name__)
AB, MetaAB — MetaB is listed second in MetaAB(MetaA, MetaB), so it takes precedence.
BA, MetaA — type(Combined) reports the "real" base metaclass, not the combined one.
CTypeError: metaclass conflict — Combined still can't resolve Base1/Base2's differing metaclasses even with MetaAB specified.
DA, MetaAB

What is the output of the following code?

javascript
from abc import ABC, abstractmethod

class Repository(ABC):
    @classmethod
    @abstractmethod
    def create(cls):
        ...

class UserRepository(Repository):
    @classmethod
    def create(cls):
        return cls.__name__

try:
    r = Repository()
except TypeError as e:
    print("TypeError:", e)

print(UserRepository.create())
ATypeError: Can't instantiate abstract class Repository without an implementation for abstract method 'create', then UserRepository
BRepository() succeeds — stacking @classmethod above @abstractmethod cancels the abstract-method check.
CTypeError on Repository(), then TypeError: create() missing 1 required positional argument: 'cls' on UserRepository.create()
DTypeError: cannot combine @classmethod and @abstractmethod

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.