Python Object-Oriented Programming Basics 5 — Questions and Answers
Question 1: What is the output of the following? ```python class A: x = 5 a = A() a.x = 10 print(A.x) ```
- 10
- 5 (Correct answer)
- AttributeError
- None
Correct answer: 5
Assigning `a.x = 10` creates an instance attribute on `a` without modifying the class attribute `A.x`, which remains 5.
Question 2: Which dunder method enables the `len(obj)` call on a custom class?
- __size__
- __length__
- __len__ (Correct answer)
- __count__
Correct answer: __len__
Python calls `__len__` on the object when `len()` is invoked, so defining it lets your class support the built-in.
Question 3: What does `issubclass(Dog, Animal)` return if `Dog` inherits from `Animal`?
- True (Correct answer)
- False
- The MRO list
- The Dog class object
Correct answer: True
`issubclass()` returns `True` when the first argument is a subclass of the second, including indirect inheritance.
Question 4: How do you make a class attribute read-only for instances?
- Prefix it with `__`
- Define it in `__slots__`
- Use `@property` with only a getter and no setter (Correct answer)
- Use `@staticmethod`
Correct 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.
Question 5: What is the purpose of `__new__` in Python classes?
- To initialize instance attributes after creation
- To allocate and return a new instance before `__init__` is called (Correct answer)
- To clone an existing instance
- To define class-level variables
Correct 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.
Question 6: In Python multiple inheritance, if two parent classes define the same method, which one is called?
- The last parent listed wins
- The first parent listed in the class definition wins (per MRO) (Correct answer)
- Python raises an error
- Both are called automatically
Correct 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.
Question 7: What does the `__iter__` method enable on a class?
- Comparison between instances
- Using the object in a `for` loop or with `iter()` (Correct answer)
- Indexing the object with `[]`
- Hashing the object for use in sets
Correct 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()`.
What is the output of the following?
```python
class A:
x = 5
a = A()
a.x = 10
print(A.x)
```