Python: Advanced (Decorators, Lambda & Exceptions)
97 cards · 🇺🇸 English
Decorators, lambda functions, exception handling, and other advanced Python concepts.
Study all 97 cards for free
Flashcards, quizzes, pixel-art games and a daily review that remembers for you.
Try the first 10 cards
1 / 10Metaclass in Python
Tap the card for the answer · swipe right if you knew it, left if not
Already have an account? Sign in
Cards
- 1Metaclass in PythonA class of a class that defines how a class behaves. type is the default metaclass. Metaclasses control class creation and can modify class attributes
- 2Create a custom metaclassclass MyMeta(type): def __new__(cls, name, bases, attrs): # modify attrs return super().__new__(cls, name, bases, attrs) class MyClass(metaclass=MyMeta): pass
- 3__new____new__ creates the instance (returns it), __init__ initializes it (returns None). __new__ is called first, receives cls; __init__ receives self
- 4Descriptor in PythonAn object that defines __get__, __set__, or __delete__ methods. Descriptors control attribute access. Used internally for properties, methods, classmethod, staticmethod
- 5Write a simple descriptorclass Descriptor: def __get__(self, obj, objtype=None): return value def __set__(self, obj, value): # set value class MyClass: attr = Descriptor()
- 6data vs non-data descriptorsData descriptor: defines __set__ or __delete__ (higher priority, checked before instance __dict__) Non-data descriptor: only __get__ (lower priority, instance __dict__ checked first)
- 7Method Resolution Order (MRO)The order in which Python searches for methods/attributes in a class hierarchy. Uses C3 linearization algorithm. View with ClassName.__mro__ or ClassName.mro()
- 8How does super() work?Returns a proxy object that delegates method calls to the next class in MRO. super().__init__() calls parent __init__ following MRO, not just direct parent
- 9__call__Makes an instance callable like a function. Called when you use obj() syntax: class Adder: def __call__(self, x, y): return x + y a = Adder() a(3, 5) # returns 8
- 10__getattr__ vs __getattribute____getattr__: called only when attribute is NOT found normally __getattribute__: called for EVERY attribute access (more powerful, more dangerous)
- 11__setattr__Called when setting ANY attribute: obj.attr = value Be careful: self.x = y inside __setattr__ causes infinite recursion! Use object.__setattr__(self, 'x', y) or __dict__
- 12__delattr__Called when deleting an attribute: del obj.attr Allows custom behavior on attribute deletion
- 13__enter__ and __exit__ used forContext manager protocol for 'with' statements: __enter__ runs at start (returns value for 'as') __exit__ runs at end (receives exception info if any)
- 14Write a simple context manager classclass MyContext: def __enter__(self): # setup return self def __exit__(self, exc_type, exc_val, exc_tb): # cleanup return False # don't suppress exceptions
- 15__slots__Restricts instance attributes to a fixed set, preventing __dict__ creation. Saves memory and provides slight performance boost: class Point: __slots__ = ['x', 'y']
- 16__str__ vs __repr____str__: human-readable string (used by str(), print()) __repr__: unambiguous representation for debugging (used by repr(), interactive shell) Goal: eval(repr(obj)) should recreate obj
- 17What comparison operators does __lt__ enable?__lt__ defines < operator. Python automatically derives <= , >, >= using functools.total_ordering decorator if you define __lt__ and __eq__
- 18Rich comparison methods__lt__ (<), __le__ (<=), __eq__ (==), __ne__ (!=), __gt__ (>), __ge__ (>=) Implement these to control comparison behavior
- 19What does __hash__ need to satisfy?Objects that compare equal must have same hash value: if a == b then hash(a) == hash(b) Hash must be immutable for object's lifetime Default: hash based on id()
- 20__bool__Defines truth value of object in boolean context (if obj:). If not defined, __len__ is checked (0 is False). If neither, object is considered True
- 21What arithmetic operators can you override?__add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), __floordiv__ (//), __mod__ (%), __pow__ (**) Also reflected versions: __radd__, __rsub__, etc.
- 22Reflected arithmetic methods__radd__, __rsub__, etc. Called when left operand doesn't support operation: 3 + obj calls obj.__radd__(3) if int doesn't have __add__ for obj's type
- 23__getitem__Enables subscript notation: obj[key] Implement for custom containers, mapping types, or sequences: class MyList: def __getitem__(self, index): return self.data[index]
- 24__setitem__Enables subscript assignment: obj[key] = value Used for mutable containers
- 25__delitem__Enables subscript deletion: del obj[key] Removes item from container
- 26__contains__Implements 'in' operator: key in obj If not defined, Python falls back to iterating and comparing with __iter__ or __getitem__
- 27__iter__ vs __next____iter__: returns iterator object (usually self) __next__: returns next value, raises StopIteration when done Together they make an object iterable
- 28__len__Returns length of container, called by len(obj) Should return non-negative integer
- 29__reversed__Returns a reverse iterator: reversed(obj) If not defined, reversed() falls back to __len__ and __getitem__
- 30__missing__ in dict subclassesCalled by __getitem__ when key is not found. Allows custom default behavior: class MyDict(dict): def __missing__(self, key): return f'default for {key}'
And 67 more cards. Study the whole deck free
Articles about this deck
More Programming decks
See all- 🐍
Python: OOP Fundamentals
59 cards · 🇺🇸 English
Classes, inheritance, and core object-oriented Python concepts.
- 🐍
Python : avancé (décorateurs, lambda et exceptions)
97 cards · 🇺🇸 English
Décorateurs, fonctions lambda, gestion des exceptions et autres concepts Python avancés.
- 🐍
Python : structures de données et compréhensions
125 cards · 🇺🇸 English
Méthodes de listes/dictionnaires/ensembles ainsi que les compréhensions de listes, de dictionnaires et de générateurs.
- 🐍
Python: Fortgeschritten (Decorators, Lambda & Exceptions)
97 cards · 🇺🇸 English
Decorators, Lambda-Funktionen, Exception-Handling und weitere fortgeschrittene Python-Konzepte.
- 🐍
Python: Funciones integradas
77 cards · 🇺🇸 English
Funciones integradas esenciales que todo desarrollador Python debería conocer.
- 🐍
Python : fondamentaux de la POO
59 cards · 🇺🇸 English
Classes, héritage et concepts fondamentaux de la programmation orientée objet en Python.
