Python Professional — Hard
Explanation
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the function they decorate.
Ready to go further?
Related questions
- What is the purpose of sys.settrace() and how does it work?
- What is the purpose of `weakref.ref()` in Python?
- What does the following code output, and what pattern does it demonstrate? class Registry: _registry = {} def __init_subclass__(cls, key=None, **kwargs): super().__init_subclass__(**kwargs) if key: Registry._registry[key] = cls class Dog(Registry, key='dog'): pass class Cat(Registry, key='cat'): pass print(Registry._registry)
- What is the Global Interpreter Lock (GIL) in CPython?
- What does the following pattern with __enter__ returning self enable? class Resource: def __enter__(self): return self def __exit__(self, *args): self.close() return False def close(self): pass with Resource() as r: print(r is not None)
- What does the following descriptor code output? class Validator: def __set_name__(self, owner, name): self.name = name def __get__(self, obj, objtype=None): if obj is None: return self return obj.__dict__.get(self.name) def __set__(self, obj, value): if not isinstance(value, int): raise TypeError(f'{self.name} must be int') obj.__dict__[self.name] = value class Point: x = Validator() p = Point() p.x = 5 print(p.x)
