Advanced OOP

Preview — 3 of 10 questions

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 PluginA(Plugin):
    pass

class PluginB(Plugin):
    pass

print([c.__name__ for c in Plugin.registry])
A['PluginA', 'PluginB']
B[]
C['Plugin', 'PluginA', 'PluginB']
DAttributeError

What is printed when the following code runs?

javascript
class LoggedAttribute:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        print(f"Setting {self.name} to {value}")
        instance.__dict__[self.name] = value

class User:
    username = LoggedAttribute()
    email = LoggedAttribute()

u = User()
u.username = "ada"
u.email = "ada@example.com"
ANothing is printed — __set_name__ never fires automatically
BSetting name to ada then Setting name to ada@example.com
CAttributeError: 'LoggedAttribute' object has no attribute 'name'
DSetting username to ada then Setting email to ada@example.com

What happens when the following code runs?

javascript
class A:
    __slots__ = ('x',)

class B:
    __slots__ = ('y',)

class C(A, B):
    pass
AC is defined successfully, combining both x and y slots.
BTypeError: multiple bases have instance lay-out conflict
CC is defined, but only x is accessible; y silently becomes a __dict__-based attribute.
DSyntaxError

Sign up free to play

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