Object-Oriented Programming Basics Flashcards
7 cards from real HACKERRANK 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 purpose of the @property decorator?
Answer: It makes an attribute read-only by default and allows controlled access via a method
@property allows a method to be accessed like an attribute, enabling getter logic without calling it with parentheses.
What does 'polymorphism' mean in the context of Python OOP?
Answer: Different classes can define the same method name with different behavior
Polymorphism allows different classes to implement the same interface (method name), with each class providing its own behavior.
Which naming convention indicates a 'protected' attribute in Python?
Answer: _attribute (single underscore)
A single leading underscore (_attr) is a convention signaling that an attribute is intended for internal use, though it's not enforced by Python.
What is name mangling in Python?
Answer: Double-underscore prefix causes Python to rewrite the attribute name to _ClassName__attr
Python applies name mangling to __attr inside a class, storing it as _ClassName__attr to avoid accidental access from subclasses.
What will this print? class Animal: def speak(self): return 'Generic' class Cat(Animal): def speak(self): return 'Meow' print(Cat().speak())
Answer: Meow
Cat overrides Animal.speak(), so Cat().speak() calls Cat's version and returns 'Meow'.
What is an abstract class in Python, and how is it created?
Answer: A class that cannot be instantiated and may define abstract methods; created using abc.ABC
Abstract classes (from the abc module) cannot be instantiated directly and use @abstractmethod to enforce method implementation in subclasses.
What does __repr__ return compared to __str__?
Answer: __repr__ returns an unambiguous developer-oriented string; __str__ returns a user-friendly string
__repr__ should return an unambiguous string useful for debugging; __str__ should return a readable string for end users.