🐍

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.

Study this deck free

Try the first 10 cards

1 / 10
Question

Metaclass in Python

Knew itLearning

Tap the card for the answer · swipe right if you knew it, left if not

Already have an account? Sign in

Cards

  1. 1Metaclass in Python
    A class of a class that defines how a class behaves. type is the default metaclass. Metaclasses control class creation and can modify class attributes
  2. 2Create a custom metaclass
    class MyMeta(type): def __new__(cls, name, bases, attrs): # modify attrs return super().__new__(cls, name, bases, attrs) class MyClass(metaclass=MyMeta): pass
  3. 3__new__
    __new__ creates the instance (returns it), __init__ initializes it (returns None). __new__ is called first, receives cls; __init__ receives self
  4. 4Descriptor in Python
    An object that defines __get__, __set__, or __delete__ methods. Descriptors control attribute access. Used internally for properties, methods, classmethod, staticmethod
  5. 5Write a simple descriptor
    class Descriptor: def __get__(self, obj, objtype=None): return value def __set__(self, obj, value): # set value class MyClass: attr = Descriptor()
  6. 6data vs non-data descriptors
    Data descriptor: defines __set__ or __delete__ (higher priority, checked before instance __dict__) Non-data descriptor: only __get__ (lower priority, instance __dict__ checked first)
  7. 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()
  8. 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. 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. 10__getattr__ vs __getattribute__
    __getattr__: called only when attribute is NOT found normally __getattribute__: called for EVERY attribute access (more powerful, more dangerous)
  11. 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. 12__delattr__
    Called when deleting an attribute: del obj.attr Allows custom behavior on attribute deletion
  13. 13__enter__ and __exit__ used for
    Context manager protocol for 'with' statements: __enter__ runs at start (returns value for 'as') __exit__ runs at end (receives exception info if any)
  14. 14Write a simple context manager class
    class MyContext: def __enter__(self): # setup return self def __exit__(self, exc_type, exc_val, exc_tb): # cleanup return False # don't suppress exceptions
  15. 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. 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
  17. 17What comparison operators does __lt__ enable?
    __lt__ defines < operator. Python automatically derives <= , >, >= using functools.total_ordering decorator if you define __lt__ and __eq__
  18. 18Rich comparison methods
    __lt__ (<), __le__ (<=), __eq__ (==), __ne__ (!=), __gt__ (>), __ge__ (>=) Implement these to control comparison behavior
  19. 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. 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
  21. 21What arithmetic operators can you override?
    __add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), __floordiv__ (//), __mod__ (%), __pow__ (**) Also reflected versions: __radd__, __rsub__, etc.
  22. 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. 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. 24__setitem__
    Enables subscript assignment: obj[key] = value Used for mutable containers
  25. 25__delitem__
    Enables subscript deletion: del obj[key] Removes item from container
  26. 26__contains__
    Implements 'in' operator: key in obj If not defined, Python falls back to iterating and comparing with __iter__ or __getitem__
  27. 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. 28__len__
    Returns length of container, called by len(obj) Should return non-negative integer
  29. 29__reversed__
    Returns a reverse iterator: reversed(obj) If not defined, reversed() falls back to __len__ and __getitem__
  30. 30__missing__ in dict subclasses
    Called 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
Study all 97 cards free