Font size
WorksheetsPython OOP Quiz
Total questions: 151
Worksheet time: 1hrs 16mins
What is the purpose of the __init__ method?
To delete an object
To initialize the object
To inherit from another class
To print values
Which of these is used to refer to the instance itself inside a class method?
self
this
cls
me
Which of the following denotes a private attribute in Python?
*name
**name
name**
name*
Which method is automatically called when an object is created?
__str__
__new__
__init__
__call__
What is the correct way to define a class named 'Car'?
def Car:
class Car():
object Car():
Car = class()
Select the valid instance attribute declarations.
self.name = name
name = self.name
self_name = name
this.name = name
Which of the following are valid visibility modifiers in Python?
Public
Protected (_)
Private (__)
Global
What is inheritance in Python used for?
To override built-in functions
To pass attributes to a class
To derive new classes from existing ones
To hide class data
Which function is used to call the parent class method?
parent()
super()
base()
main()
What does MRO stand for in Python?
Method Run Order
Method Resolution Order
Multiple Resolution Output
Main Root Order
Which type of inheritance leads to the diamond problem?
Single
Multiple
Multilevel
Hierarchical
What keyword is used to inherit from a base class?
extends
inherits
super
class Derived(Base):
Choose the correct example of multiple inheritance.
class C(A, B):
class C(B -> A):
class C = A + B:
class C inherit A, B
Select all the classes involved in MRO.
Base class
Derived class
Sibling class
Interface class
What are the benefits of using super() in inheritance?
Calls the base class constructor
Avoids hardcoding class names
Improves maintainability
Slows down performance
What does polymorphism allow in OOP?
Use same name methods for different classes
Overload constructors
Create multiple instances
Hide data
Which method can be overridden in a subclass?
Any method
Only static methods
Only private methods
Only class methods
Which module provides abstract base classes in Python?
abc
abstract
base
interface
Which decorator is used to declare an abstract method?
@classmethod
@abstractmethod
@staticmethod
@override
Polymorphism can be achieved through:
Method overriding
Method hiding
Method chaining
Method duplication
Select all that apply to abstract classes:
Can contain abstract methods
Cannot be instantiated
Must override all methods
Defined using 'abc' module
Which of these describe polymorphism?
One interface, multiple implementations
Single inheritance only
Multiple classes with same methods
Overriding methods
What is encapsulation in OOP?
Hiding internal state
Accessing private data
Using multiple classes
Calling superclass methods
Which keyword is used to create a property in Python?
@getter
@access
@property
@value
What is the purpose of getter methods?
To modify data
To return attribute values
To initialize class
To set property values
Select all the benefits of using @property:
Controlled access
Validation
Cleaner syntax
Multiple inheritance
Which decorators are typically used for controlled access?
@property
@<property>.setter
@classmethod
@staticmethod
Which of these demonstrate encapsulation?
Private attributes
Getters and setters
Inheritance
Global variables
How can you define a setter in Python?
@property_name.setter
@setter.property
@property.setter
@setproperty
What will be the output?
class A:
def process(self):
print("A.process")
class B(A):
def process(self):
super().process()
print("B.process")
class C(A):
def process(self):
super().process()
print("C.process")
class D(B, C):
def process(self):
super().process()
print("D.process")
d = D()
d.process()
A.process B.process C.process D.process
A.process C.process B.process D.process
D.process B.process C.process A.process
B.process C.process D.process A.process
Which methods will be executed in order?
class Base:
def call(self):
print('Base')
class Left(Base):
def call(self):
super().call()
print('Left')
class Right(Base):
def call(self):
super().call()
print('Right')
class Sub(Left, Right):
def call(self):
super().call()
print('Sub')
s = Sub()
s.call()
Base → Right → Left → Sub
Base → Left → Right → Sub
Sub → Left → Right → Base
Base → Right → Sub → Left
What will the following output?
class Parent:
value = 100
class Child(Parent):
def init(self):
self.value = 200
c = Child()
print(c.value)
print(Child.value)
print(Parent.value)
200 200 100
200 100 100
100 200 100
200 100 200
Identify the error in this code:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
pass
c = Circle()
print(c.area())
No error, output is None
Circle must implement area() method
Shape class is wrong
circle() constructor is missing arguments
What will be printed?
5
10
Error
None
What will be the output of the following code?
Animal speaks
Dog barks
Error
Nothing
What attribute will the object 'p' have after this code?
name
self
p
Alice
Which method will be called when creating an object?
__init__
hello
__new__
self
What will the following print?
A
B
A B
B A
What is printed?
4
Error
None
Undefined
Which line properly creates a private attribute?
self.hidden
self._hidden
self.__hidden
hidden
What is the method resolution order for this hierarchy?
D → B → A → C
D → B → C → A
D → C → B → A
D → A → B → C
Which decorator is used to define a getter property?
@getter
@property
@age
@get_age
What does the following code do?
Prints 5
Error
Prints None
Prints _value
What will happen?
Dog runs
Error because of abstract method
Nothing
Dog walks
What programming paradigm focuses on data flow and avoids changing state?
Procedural
Functional
Object-oriented
Declarative
Which OOP concept restricts direct access to an object's data and behavior?
Inheritance
Composition
Encapsulation
Polymorphism
A class is best described as:
A reusable function
A blueprint for creating objects
A special loop structure
A method container
When one class derives features from another, it's called:
Abstraction
Encapsulation
Inheritance
Reflection
Which concept allows methods to behave differently based on the object?
Inheritance
Overloading
Polymorphism
Shadowing
What defines a class instance in memory?
Class name
Object
Attribute
Module
What function initializes object attributes upon instantiation?
del
init
call
setup()
What keyword refers to the current object within class methods?
self
this
obj
ref
Which symbol combination is typically used for private attributes?
--name
name__
__name
_name
How can you define a variable visible to all instances?
self.variable
_variable
ClassName.variable
var = 0 in init
Which function returns a readable string of an object?
describe
string
str
text
How can child classes access superclass protected members?
Through imports
Using super ()
Via private access
With decorators
Which function allows invocation of a superclass's method?
parent.method()
base ()
super ()
root.method()
If a class inherits from more than one class, it's called:
Interface merging
Multilevel hierarchy
Multiple inheritance
Deep linking
What does MRO help determine?
Object creation speed
Method call sequence
Memory reference optimization
Recursive class calls
What issue arises from complex multiple inheritance?
Shadowing
Method overuse
Diamond problem
Recursive constructors
Which method is used first when instantiating subclasses?
parent's call
init of child
setup
build()
Is it possible to restrict multiple inheritance in Python?
No, it's always allowed
Only via metaclasses
Yes, with private inheritance
Yes, using single base class policy
Changing behavior of a method in a child class is called:
Hiding
Overriding
Inverting
Swapping
To enforce method implementation in subclasses, use:
@enforce
@abstractmethod
@virtual
override()
Which decorator makes a method abstract inside a class?
@abstractmethod
@pure
@virtualmethod
@interface
Can instances of abstract classes be created directly?
Only with init override
No
Yes, if it has no methods
Yes, with metaclass tricks
What makes polymorphism useful?
Reduces subclassing
Enables uniform interfaces
Limits method visibility
Prevents overrides
When different classes implement the same interface, it's called:
Polymorphism
Abstraction
Composition
Overloading
What output will this code produce?
A
B
Error
Nothing
In which case is an attribute considered private?
data
_temp
__secret
All of them
Which method influences print(obj) output?
__str__
__format__
__show__
display()
Interfaces in Python are implemented via:
Abstract base classes
Decorators
Class templates
Metaclasses only
To avoid method replacement in child classes, use:
@final (Python 3.8+)
@readonly
No such protection exists
Use underscore prefixes
What causes an error here?
Works fine
x is undefined due to missing super ()
y hides x
Class syntax is wrong
Purpose of @staticmethod:
A) Prevent inheritance
A) Allow function without object reference
A) Create shared state
A) Track method calls
What does "duck typing" mean?
Interface-based variable hints
Behavior determines object compatibility
Compiler-style typing
Static interface checks
Which principle is violated here?
class Account:
def init(self):
self.__balance = 100
print(Account().__balance)
Polymorphism
Abstraction
Encapsulation
Composition
Which method runs upon object deletion?
__exit__
__destroy__
__del__
__remove__
What will be printed?
From object
From class
Nothing
Error
Which decorator allows access to the method from class and not just instances?
@classmethod
@staticmethod
@abstractmethod
@getmethod
What is the main purpose of encapsulation in OOP?
To make all class members publicly accessible
To hide implementation details from outside access
To prevent class inheritance
To improve code execution speed
Which symbol prefix indicates a private attribute in Python?
No prefix
Single underscore (_)
Double underscore (__)
Asterisk (*)
What does the @property decorator do?
Makes a method act like a class method
Converts a method into a read-only attribute
Prevents method overriding
Marks a method as deprecated
How do you define a setter for a property named 'price'?
@price.setter
@setter(price)
@property.setter
@set_price
Which of these is a protected attribute in Python?
self.name
self._name
self.__name
self.name*
Which magic method is called by the print() function?
__repr__
__str__
__print__
__display__
What is the purpose of the __len__ method?
To compare object sizes
To return the length of an object
To initialize object counters
To enable string conversion
Which magic method is called when using the + operator?
__plus__
__add__
__sum__
__concat__
What does the __call__ method enable?
Object comparison
Object initialization
Calling objects like functions
Object serialization
Which method implements the == comparison?
__eq__
__cmp__
__same__
__compare__
What is the correct structure for exception handling?
try -> catch -> finally
try -> except -> finally
attempt -> handle -> ensure
begin -> rescue -> end
Which block always executes, even if an exception occurs?
try
except
finally
else
How do you create a custom exception class?
A) class MyError(Exception)
A) def MyError()
A) exception MyError:
A) new Exception("MyError")
Which exception occurs when a key isn't found in a dictionary?
ValueError
KeyError
IndexError
AttributeError
What does the raise keyword do?
Catches an exception
Creates a new exception type
Triggers an exception manually
Silences an exception
Which file mode opens for writing without overwriting?
"w"
"r"
"a"
"x"
What does json.loads() do?
Converts JSON to Python object
Converts Python object to JSON
Reads JSON from a file
Validates JSON syntax
Which module handles binary serialization?
json
pickle
yaml
marshal
What is the correct way to read all lines from a file?
file.read()
file.readlines()
file.line()
file.get_lines()
What does serialization mean?
Sorting data alphabetically
Converting objects to storable formats
Encrypting sensitive data
Compressing file sizes
What is the default metaclass in Python?
object
type
class
meta
Which method is called first when creating an instance?
__init__
__new__
__call__
__create__
What does type ('MyClass', (), {}) do?
Checks variable type
Creates a new class dynamically
Converts values to strings
Compares two classes
When is __new__ executed?
Before __init__
After __init__
Instead of __init__
During class destruction
What best describes a metaclass?
A superclass for all exceptions
A class that creates other classes
A decorated method
An abstract base class
What does the Singleton pattern ensure?
Only one instance exists
Multiple interchangeable algorithms
One-to-many notifications
Dynamic behavior addition
Which pattern delegates object creation to subclasses?
Observer
Factory Method
Decorator
Strategy
In the Observer pattern, who receives updates?
The main subject
Registered observers
Factory objects
Decorator classes
What does the Decorator pattern do?
Adds responsibilities dynamically
Ensures single instance
Creates object families
Encapsulates algorithms
Which pattern selects algorithms at runtime?
Singleton
Strategy
Observer
Factory
What is the purpose of getter methods?
To modify private attributes directly
To return attribute values safely
To initialize class instances
To delete object properties
Which magic method provides an "official" string representation?
__str__
__repr__
__print__
__info__
What happens if you don't handle an exception?
Program continues silently
Program terminates with error
Exception is logged automatically
Default values are substituted
What is the main advantage of using JSON over pickle?
Better performance
Language independence
Supports binary data
Smaller file sizes
Which pattern notifies dependents of state changes?
Singleton
Strategy
Observer
Factory
What is the primary purpose of the Singleton pattern?
Allow creation of multiple instances of a class
Ensure only one instance of a class exists
Define interchangeable algorithms
Construct complex objects
Which pattern allows dynamically adding new responsibilities to an object at runtime?
Strategy
Observer
Decorator
Factory Method
The Factory Method pattern encapsulates object creation by using:
A global function
A static factory class
A method that returns instances of various subclasses
A class decorator
In the Observer pattern, the subject notifies observers of state changes by invoking:
Direct attribute access
Observer callbacks
Raising exceptions
Polling in a loop
The Strategy pattern is useful when you need to:
Create singleton instances
Select an algorithm at runtime
Enforce a strict class hierarchy
Track state changes of an object
Which technique in Python is often used to implement the Singleton pattern?
A metaclass that caches instances
Overriding __call__ in each subclass
Decorating methods with @staticmethod
Declaring all methods as @classmethod
What role does the metaclass abc.ABCMeta play?
Enables dynamic code generation
Forces subclasses to implement abstract methods
Implements the Singleton pattern
Manages thread synchronization
To avoid subclass explosion when combining different behaviors, which pattern is suitable?
Singleton
Decorator
Adapter
Observer
In the threading module, which method starts a new thread?
run()
start()
init()
spawn()
Which lock allows the same thread to acquire it multiple times without blocking?
Lock
RLock
Semaphore
Event
What does GIL stand for in Python?
Global Interpreter Lock
General Instance Level
Global Instance Loader
Generic Integration Layer
To bypass the GIL and achieve true parallelism, you should use:
threading
asyncio
multiprocessing
concurrent.futures
To protect shared data from race conditions, you should wrap access in:
with open block
with lock block
try/except block
for loop
If two threads modify the same variable without synchronization, this leads to a:
Deadlock
Race condition
Memory leak
Type error
Which call waits for a thread to complete?
thread.join()
thread.wait()
thread.stop()
thread.sync()
On Windows, the default start method for multiprocessing is:
fork
spawn
forkserver
thread
In Flask, if unspecified, a route accepts which HTTP method by default?
GET
POST
PUT
DELETE
Which Django CBV class renders a list of model instances?
DetailView
ListView
FormView
TemplateView
To create a new Django project, you run:
django-admin startapp
django-admin startproject
python manage.py initproject
flask new project
In SQLAlchemy (Flask), sessions are created via:
Session()
sessionmaker()
engine.connect()
create_session()
In which Django file are URL routes defined?
models.py
views.py
urls.py
settings.py
In Flask, what is a Blueprint used for?
Grouping related routes and templates
Managing static files
Configuring the database
Running background tasks
What is the default template engine in Django called?
Jinja2
Mustache
Django Template Language
Mako
To create and apply migrations in Django, you run:
makemigrations then migrate
migrate then makemigrations
db init
syncdb
Which UML diagram shows classes, their attributes, methods, and relationships?
Use case diagram
Activity diagram
Class diagram
Sequence diagram
Which phase usually comes first in software development?
Testing
Requirements analysis
Implementation
Deployment
Which Sphinx extension automatically documents Python modules?
sphinx.ext.autodoc
sphinx.ext.viewcode
sphinx.ext.napoleon
sphinx.ext.todo
What does Continuous Integration (CI) primarily provide?
Automated build and test
Manual code review
Real-time chat
Deployment scripts only
To inspect the Method Resolution Order (MRO) in Python, you can check:
Class.__mro__
class.mro()
inspect.mro(class)
All of the above
Which function serializes a Python object to a JSON-formatted string?
json.dumps()
pickle.dumps()
marshal.dumps()
yaml.dump()
What will be printed? class X: def run(self): print("X") class Y(X): def run(self): print("Y") super().run() class Z(X): def run(self): super().run() print("Z") class W(Y, Z): def run(self): super().run() print("W") w = W() w.run()
Y X Z W
X Y Z W
Y Z X W
X Z Y W
What will be printed? class A: def __init__(self): print("A", end="") class B(A): def __init__(self): print("B", end="") super().__init__() class C(A): def __init__(self): super().__init__() print("C", end="") class D(B, C): def __init__(self): print("D", end="") super().__init__() d = D()
DBAC
DBCA
DABC
DCBA
What will be printed? class A: x = "A" class B(A): x = "B" class C(A): pass class D(C, B): pass print(D.x)
A
B
C
Error
What will be printed? class A: def __init__(self): self.value = 1 class B(A): def __init__(self): self.value = 2 super().__init__() b = B() print(b.value)
1
2
3
Error
Which Django management command runs unit tests?
manage.py runserver
manage.py test
manage.py migrate
manage.py makemigrations
Which tool can you use to check Python code style before an exam?
pytest
pylint
unittest
coverage
