OOP Flashcards
(17 cards)
What is a constructor in Python?
A special method named __init__ that sets up the initial state of an object.
What’s the difference between public, private, and protected attributes?
Public: self.x – accessible anywhere
Protected: self._x – internal use, subclasses OK
Private: self.__x – not accessible outside class
What is inheritance?
A class (child) can inherit methods and properties from another class (parent).
What is polymorphism in OOP?
Different classes can define the same method, and the correct version is chosen at runtime.
What does super() do?
Calls the method of the superclass (usually the parent class version of a method).
What is an abstract class?
A class that cannot be instantiated and is meant to be inherited.
How do you force a subclass to implement a method?
Use @abstractmethod from the abc module.
What is composition?
A class contains another class (has-a relationship); the composed object is owned.
What does open(‘file.txt’, ‘r’) do?
Opens a file for reading.
What’s the difference between ‘w’ and ‘a’ modes?
‘w’ overwrites, ‘a’ appends.
What does assert do in testing?
Checks that an expression is True. If not, raises an AssertionError.
What is pytest used for?
Automated unit testing in Python.
What’s the structure of a try-except block?
try:
# risky code
except ErrorType:
# handle error
What does raise do?
Manually triggers an exception.
What is the ternary operator syntax?
x = “yes” if condition else “no”
What does isinstance(obj, Class) do?
Returns True if obj is an instance of Class.
What is a Python property?
A way to use getters and setters like attributes with @property.