All quizzesHard
OOP Internals
Preview — 3 of 10 questions
What happens when the following code runs?
javascript
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
class C(A, B):
passAC is created successfully, using type as its metaclass, since neither MetaA nor MetaB was explicitly requested for C.
BTypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
CSyntaxError
DC is created successfully, using MetaA (the first base's metaclass) automatically.
What is the print order when the following code runs?
javascript
class OrderTrackingMeta(type):
@classmethod
def __prepare__(mcs, name, bases):
print("preparing namespace")
return {}
def __new__(mcs, name, bases, namespace):
print("creating class")
return super().__new__(mcs, name, bases, namespace)
class Foo(metaclass=OrderTrackingMeta):
x = 1Acreating class then preparing namespace
BOnly preparing namespace is printed — __new__ is skipped since __prepare__ already returned the namespace.
CNeither is printed — both hooks require an explicit call.
Dpreparing namespace then creating class
What is printed when the following code runs?
javascript
class Base:
def __init__(self, **kwargs):
print("Base kwargs:", kwargs)
class LoggingMixin:
def __init__(self, verbose=False, **kwargs):
self.verbose = verbose
super().__init__(**kwargs)
class Widget(LoggingMixin, Base):
def __init__(self, name, **kwargs):
self.name = name
super().__init__(**kwargs)
w = Widget(name="Button", verbose=True, color="red")
print(w.verbose, w.name)ABase kwargs: {'color': 'red'} then True Button
BBase kwargs: {'color': 'red'} then False Button
CTypeError: __init__() got an unexpected keyword argument 'color'
DBase kwargs: {'verbose': True, 'color': 'red'} then True Button
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.