Python From Beginner to Advanced

0% completed

Previous
Next
Quiz
What is the primary benefit of using Object-Oriented Programming (OOP) in Python?
A
To enhance the speed of programs.
B
To facilitate code reuse through inheritance.
C
To reduce memory usage.
D
To increase execution time of functions.
What will the following Python code output?
class Dog:
    def bark(self):
        return "Woof!"

fido = Dog()
print(fido.bark())
A
Woof!
B
bark
C
Dog
D
Error
What is the purpose of the double underscore (__) prefix in Python?
Choose all correct options
It converts a variable into a constant.
It deletes the variable from memory.
It indicates a strongly private variable or method.
It is used for variable name mangling in inheritance.
Consider the following code snippet. What is its output?
class Car:
    __max_speed = 100  # Private variable
    def drive(self):
        return f"Driving max speed at {self.__max_speed} km/h"

my_car = Car()
print(my_car.drive())
A
Driving max speed at 100 km/h
B
AttributeError
C
Driving max speed at km/h
D
None
What does the following code demonstrate?
class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

pet = Dog()
print(pet.speak())
A
Polymorphism
B
Encapsulation
C
Abstraction
D
None of the above
What is the primary purpose of an abstract class in Python?
A
To enhance performance by abstracting data details
B
To create a blueprint for other classes to implement specific methods
C
To directly instantiate objects from abstract classes
D
To restrict access to methods in the derived classes
Analyze the following Python code using abstraction. What will happen if you try to instantiate the Shape class?
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

shape = Shape()
A
An instance of Shape will be created without any issue.
B
The code will raise a TypeError because abstract classes cannot be instantiated.
C
The area method will return None.
D
Python will ignore the abstract method and create an instance of Shape.
In the context of encapsulation, what does the following Python code demonstrate?
class BankAccount:
    def __init__(self):
        self.__balance = 0  # private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            self.__update_ledger(amount)

    def __update_ledger(self, amount):
        print(f"Deposited: {amount}")

account = BankAccount()
account.deposit(100)
A
The __update_ledger method is publicly accessible and can be called on any instance.
B
The deposit method is incorrectly handling private methods.
C
There is a syntax error with the double underscore prefix.
D
The code shows an example of using public methods to modify private attributes.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next