PCAP Object-Oriented Programming 1 — Questions and Answers
Question 1: Which keyword is used to define a class in Python?
- def
- class (Correct answer)
- object
- struct
Correct answer: class
The `class` keyword is used to define a class in Python.
Question 2: What is the purpose of the `__init__` method in a Python class?
- To destroy an object
- To initialize a new instance (Correct answer)
- To copy an object
- To define class variables
Correct answer: To initialize a new instance
`__init__` is the constructor method called automatically when a new object is created.
Question 3: How do you create an instance of a class named `Car`?
- Car.new()
- new Car()
- Car() (Correct answer)
- instance(Car)
Correct answer: Car()
You instantiate a class by calling it like a function: `Car()`.
Question 4: What does the `self` parameter represent in a Python class method?
- The class itself
- The parent class
- The current instance (Correct answer)
- A global variable
Correct answer: The current instance
`self` refers to the current object instance on which the method is being called.
Question 5: Which method is called when an object is deleted or garbage collected?
- __init__
- __del__ (Correct answer)
- __end__
- __destroy__
Correct answer: __del__
`__del__` is the destructor method called when an object is about to be destroyed.
Question 6: What is encapsulation in object-oriented programming?
- Inheriting methods from a parent class
- Bundling data and methods within a class (Correct answer)
- Using multiple classes at once
- Overriding parent methods
Correct answer: Bundling data and methods within a class
Encapsulation bundles data (attributes) and behavior (methods) together inside a class.
Which keyword is used to define a class in Python?