06.01 Building Classes And Composition - Quiz¶
Check your understanding
-
What is the primary purpose of the
__init__method in a Python class?- To delete objects when they’re no longer needed
- To initialize a new object’s attributes and set up its initial state { data-correct }
- To define what methods the class can use
- To create multiple copies of the class
-
Which parameter must always be the first parameter in instance methods?
clsself{ data-correct }thisinstance
-
What does this code create?
- A class definition
- An instance (object) of the Student class { data-correct }
- A method call
- A constructor definition
-
What is composition in object-oriented programming?
- Inheriting from multiple parent classes
- Building complex objects by combining simpler component objects { data-correct }
- Writing longer methods with more functionality
- Using global variables in classes
-
Why is “composition over inheritance” often preferred?
- Composition is always faster than inheritance
- Composition provides more flexibility and looser coupling { data-correct }
- Inheritance is deprecated in modern programming
- Composition uses less memory
-
Look at this class structure. What principle does it demonstrate?
- Inheritance
- Composition { data-correct }
- Encapsulation
- Polymorphism
-
What makes a class “cohesive”?
- It has many different responsibilities
- It has a single, well-defined purpose with related methods { data-correct }
- It inherits from multiple parent classes
- It has more than 10 methods
-
Which constructor design is better?
def __init__(self, name, age): self.name = name self.age = age def __init__(self, name, age): if not name or age < 0: raise ValueError("Invalid input") self.name = name self.age = age- Option A - simpler code
- Option B - includes validation { data-correct }
- Both are equally good
- Neither is correct
-
What relationship does composition represent?
- “is-a” relationship
- “has-a” relationship { data-correct }
- “uses-a” relationship
- “extends-a” relationship
-
In this example, what type of
_calculate_total?method isclass ShoppingCart: def add_item(self, item): pass def _calculate_total(self): pass def get_total(self): return self._calculate_total()- Public method intended for external use
- Private helper method for internal use { data-correct }
- Static method that doesn’t use instance data
- Abstract method that must be overridden