Python Object-Oriented Programming Basics 2 — Questions and Answers
Question 1: What does the `super()` function do in Python?
- Deletes the parent class
- Calls a method from the parent class (Correct answer)
- Creates a new subclass
- Overrides all parent methods
Correct answer: Calls a method from the parent class
`super()` returns a proxy object that delegates method calls to a parent class, enabling cooperative multiple inheritance.
Question 2: Which of the following correctly defines a class method in Python?
- def method(self):
- @staticmethod def method(cls):
- @classmethod def method(cls): (Correct answer)
- @classmethod def method(self):
Correct answer: @classmethod def method(cls):
Class methods are decorated with `@classmethod` and receive the class itself as the first argument, conventionally named `cls`.
Question 3: What is the output of `type(42)` in Python?
- int
- <class 'int'> (Correct answer)
- number
- Integer
Correct answer: <class 'int'>
`type()` returns the class object of the argument, displayed as `<class 'int'>` for integers.
Question 4: Which magic method is called when an object is created?
- __start__
- __new__
- __init__ (Correct answer)
- __create__
Correct answer: __init__
`__init__` is called after the object is created to initialize its attributes; `__new__` allocates it but is rarely overridden.
Question 5: What does name mangling do in Python (e.g., `__attr`)?
- Makes the attribute completely private
- Renames the attribute to `_ClassName__attr` (Correct answer)
- Deletes the attribute on assignment
- Converts the attribute to a class variable
Correct answer: Renames the attribute to `_ClassName__attr`
Python mangles `__attr` to `_ClassName__attr` to reduce accidental override in subclasses, but it is still accessible.
Question 6: What is an abstract class in Python?
- A class with no methods
- A class that cannot be instantiated directly and must be subclassed (Correct answer)
- A class defined inside another class
- A class with only class variables
Correct answer: A class that cannot be instantiated directly and must be subclassed
Abstract classes, created with `abc.ABC`, contain abstract methods that subclasses must implement before instantiation.
Question 7: Which statement about `__str__` and `__repr__` is correct?
- `__str__` is for developers; `__repr__` is for end users
- `__repr__` is for developers; `__str__` is for end users (Correct answer)
- Both always produce identical output
- `__repr__` is only called by `print()`
Correct answer: `__repr__` is for developers; `__str__` is for end users
`__repr__` should return an unambiguous developer-friendly string; `__str__` provides a readable user-facing string.
What does the `super()` function do in Python?