Object-Oriented Programming Basics Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Object-Oriented Programming Basics flashcards as text
What is the output of the following? ```python class A: x = 5 a = A() a.x = 10 print(A.x) ```
Answer: 5
Assigning `a.x = 10` creates an instance attribute on `a` without modifying the class attribute `A.x`, which remains 5.
Which dunder method enables the `len(obj)` call on a custom class?
Answer: __len__
Python calls `__len__` on the object when `len()` is invoked, so defining it lets your class support the built-in.
What does `issubclass(Dog, Animal)` return if `Dog` inherits from `Animal`?
Answer: True
`issubclass()` returns `True` when the first argument is a subclass of the second, including indirect inheritance.
How do you make a class attribute read-only for instances?
Answer: Use `@property` with only a getter and no setter
A `@property` with only a getter raises `AttributeError` on assignment, effectively making the attribute read-only from outside.
What is the purpose of `__new__` in Python classes?
Answer: To allocate and return a new instance before `__init__` is called
`__new__` is a static method that creates and returns the new object; `__init__` then initializes it.
In Python multiple inheritance, if two parent classes define the same method, which one is called?
Answer: The first parent listed in the class definition wins (per MRO)
Python's C3 MRO resolves conflicts by prioritizing the first listed parent, then proceeds left-to-right through the hierarchy.
What does the `__iter__` method enable on a class?
Answer: Using the object in a `for` loop or with `iter()`
Defining `__iter__` (and `__next__`) makes an object iterable, allowing it to be used in `for` loops, comprehensions, and `iter()`.