Python Professional — Hard
Explanation
The output is "True then None" because the weak reference to the object is still valid when checked, but returns None after the object is deleted.
Ready to go further?
Related questions
- What is the output of the following code involving __missing__? class DefaultList(dict): def __missing__(self, key): self[key] = [] return self[key] d = DefaultList() d['a'].append(1) d['a'].append(2) d['b'].append(3) print(d)
- What does the following code output? class MyInt(int): def __new__(cls, value): return super().__new__(cls, value * 2) x = MyInt(5) print(x, type(x))
- What does the following code demonstrate about Python's GC and reference cycles? import gc class Node: def __init__(self): self.ref = None a = Node() b = Node() a.ref = b b.ref = a del a, b print(gc.collect())
- What is the output of the following code? class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance a = Singleton() b = Singleton() print(a is b, id(a) == id(b))
- What does the following code output? def make_counter(): count = 0 def increment(n=1): nonlocal count count += n return count def reset(): nonlocal count count = 0 increment.reset = reset return increment c = make_counter() c(3) c(2) c.reset() print(c())
- What is the output of the following code? def decorator(cls): original_init = cls.__init__ def new_init(self, *args, **kwargs): original_init(self, *args, **kwargs) self.decorated = True cls.__init__ = new_init return cls @decorator class Foo: def __init__(self): self.value = 1 f = Foo() print(f.value, f.decorated)
