OOP Internals — Series 3

Preview — 3 of 10 questions

What is the output of the following code?

javascript
class Flyweight(type):
    _instances = {}
    def __call__(cls, key):
        if key not in cls._instances:
            cls._instances[key] = super().__call__(key)
        return cls._instances[key]

class Color(metaclass=Flyweight):
    def __init__(self, key):
        self.key = key

c1 = Color("red")
c2 = Color("red")
c3 = Color("blue")
print(c1 is c2)
print(c1 is c3)
print(len(Flyweight._instances))
ATrue, False, 2
BFalse, False, 3
CTrue, True, 1
DFalse, True, 2

What is the output of the following code?

javascript
import weakref

class Handler:
    def on_event(self):
        return "handled"

h = Handler()
plain_ref = weakref.ref(h.on_event)
weak_method = weakref.WeakMethod(h.on_event)

print(plain_ref() is None)
print(weak_method()())
del h
print(weak_method() is None)
AFalse, handled, True
BTrue, handled, True
CFalse, handled, False
DTrue, AttributeError: 'NoneType' object has no attribute..., True

What is the output of the following code?

javascript
class Plugin:
    registry = []
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry.append(cls)

class Alpha(Plugin):
    pass

class Beta(Plugin):
    pass

print([c.__name__ for c in Plugin.registry])
A['Beta', 'Alpha']
B['Plugin', 'Alpha', 'Beta']
C['Alpha', 'Beta']
D[]

Sign up free to play

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