Python OOP MCQs

1 min read

Object-Oriented Programming (OOP) in Python is a programming paradigm that uses classes and objects to model real world entities, promoting code reusability, modularity, and organization. Core principles include inheritance, polymorphism, encapsulation, and abstraction, which allow developers to build scalable applications. Python supports these concepts seamlessly through built-in syntax structures, constructor methods like init, and special magic methods. These practice MCQs are designed to test and reinforce your grasp of Python’s object-oriented principles for exams and technical interviews.

1. Which of the following describes the mechanism of acquiring properties and behaviors of a base class by a derived class in Python?

a) Polymorphism
b) Inheritance
c) Encapsulation
d) Abstraction
Correct Answer: b) Inheritance
Explanation:
Inheritance allows a derived class to inherit attributes and methods from a base class, promoting code reusability.

2. What is the name of the reference variable passed as the first argument to instance methods in Python classes by convention?

a) self
b) this
c) cls
d) instance
Correct Answer: a) self
Explanation:
By convention, 'self' is used as the first parameter name in instance methods to refer to the instance invoking the method.

3. Which built-in decorator is used to define a class method in Python?

a) @staticmethod
b) @classmethod
c) @property
d) @method
Correct Answer: b) @classmethod
Explanation:
The @classmethod decorator binds the method to the class rather than its instance, passing the class itself as the first argument (cls).

4. How do you define a private attribute in a Python class to invoke name mangling?

a) Using a single leading underscore (_attr)
b) Using double leading underscores (__attr)
c) Using a trailing underscore (attr_)
d) Using the private keyword
Correct Answer: b) Using double leading underscores (__attr)
Explanation:
Double leading underscores trigger name mangling in Python, prefixing the attribute name with '_ClassName'.

5. Which special method is invoked when an object is garbage collected or destroyed?

a) __init__
b) __del__
c) __destroy__
d) __free__
Correct Answer: b) __del__
Explanation:
The __del__ method is known as the destructor and is called when an instance is about to be destroyed.

6. What function is used to return a proxy object that delegates method calls to a parent or sibling class?

a) parent()
b) super()
c) base()
d) inherits()
Correct Answer: b) super()
Explanation:
The super() function returns a proxy object that allows you to call methods of the parent or sibling classes.

7. Which of the following allows an attribute to be accessed like a regular attribute while being computed dynamically via a method?

a) @property
b) @compute
c) @dynamic
d) @attribute
Correct Answer: a) @property
Explanation:
The @property decorator allows methods to be accessed like attributes, executing getter logic behind the scenes.

8. What is multiple inheritance?

a) A class inheriting from a single base class multiple times
b) A class inheriting from more than one base class
c) Multiple classes inheriting from the same base class
d) A class having multiple instances
Correct Answer: b) A class inheriting from more than one base class
Explanation:
Multiple inheritance occurs when a derived class inherits features from multiple parent classes.

9. What order does Python use to resolve method lookup in multiple inheritance hierarchies?

a) Depth-First Search (DFS)
b) Method Resolution Order (MRO) using C3 Linearization
c) Breadth-First Search (BFS)
d) Random Order Selection
Correct Answer: b) Method Resolution Order (MRO) using C3 Linearization
Explanation:
Python computes an MRO using the C3 linearization algorithm to ensure monotonic and consistent method resolution.

10. Which attribute can be used to check the method resolution order of a class?

a) __order__
b) __mro__
c) __hierarchy__
d) __path__
Correct Answer: b) __mro__
Explanation:
The __mro__ tuple attribute provides the method resolution order for a given class.

11. Which module in Python provides abstract base classes (ABCs)?

a) abc
b) abstract
c) interfaces
d) baseclass
Correct Answer: a) abc
Explanation:
The 'abc' module provides infrastructure for defining Abstract Base Classes in Python.

12. How do you declare an abstract method in an Abstract Base Class?

a) @abstract
b) @abstractmethod
c) virtual def
d) abstract def
Correct Answer: b) @abstractmethod
Explanation:
The @abstractmethod decorator marks methods as abstract, requiring subclasses to implement them.

13. Can an abstract base class be instantiated directly in Python?

a) Yes, always
b) No, it raises a TypeError if it has abstract methods
c) Yes, but only if all methods are empty
d) Only via special factory methods
Correct Answer: b) No, it raises a TypeError if it has abstract methods
Explanation:
Instantiation of an ABC fails with a TypeError if any abstract methods remain unimplemented in the class or its subclasses.

14. What is duck typing in Python?

a) Checking object type explicitly using isinstance()
b) A programming style where an object's suitability is determined by the presence of methods and properties rather than explicit inheritance
c) Casting variables to bird-related classes
d) Strict type checking enforced at runtime
Correct Answer: b) A programming style where an object's suitability is determined by the presence of methods and properties rather than explicit inheritance
Explanation:
Duck typing focuses on what an object can do ('If it walks like a duck and quacks like a duck...') rather than its class hierarchy.

15. Which special method defines the behavior of the addition operator (+)?

a) __add__
b) __plus__
c) __sum__
d) __combine__
Correct Answer: a) __add__
Explanation:
The __add__ special method implements behavior for the binary addition operator (+).

16. What is operator overloading?

a) Writing too many functions in one class
b) Giving standard operators custom meanings for user-defined classes
c) Executing operators in parallel threads
d) Passing excessive arguments to an operator
Correct Answer: b) Giving standard operators custom meanings for user-defined classes
Explanation:
Operator overloading lets classes define custom implementations for built-in operators like +, -, and *.

17. Which special method returns the length of an object when using the len() function?

a) __size__
b) __length__
c) __len__
d) __count__
Correct Answer: c) __len__
Explanation:
The len() function invokes the __len__ special method on the target object.

18. What does the @staticmethod decorator indicate?

a) The method receives the class as the first argument
b) The method receives neither 'self' nor 'cls', acting like a regular function housed inside a class namespace
c) The method cannot be modified
d) The method is executed only once
Correct Answer: b) The method receives neither 'self' nor 'cls', acting like a regular function housed inside a class namespace
Explanation:
Static methods do not receive any implicit first arguments and behave like normal functions grouped inside a class for logical scoping.

19. Which function returns a boolean indicating whether a class is a subclass of another class?

a) issubclass()
b) isinstance()
c) checksub()
d) hassubclass()
Correct Answer: a) issubclass()
Explanation:
The issubclass(class, classinfo) built-in function checks if a class is a subclass of another.

20. What happens when you print an instance of a user-defined class that does not implement __str__ or __repr__?

a) It raises a RuntimeError
b) It prints a default string containing the object's memory address and class name
c) It prints nothing
d) It prints an empty string
Correct Answer: b) It prints a default string containing the object's memory address and class name
Explanation:
Without __str__ or __repr__, Python falls back to object's default representation showing the class name and hexadecimal memory address.

21. Which special method is called when an object is formatted using formatted string literals (f-strings) or str.format()?

a) __format__
b) __str__
c) __print__
d) __display__
Correct Answer: a) __format__
Explanation:
The __format__ special method customizes how an object is formatted inside f-strings or str.format().

22. How do you invoke a setter method associated with a property named 'score'?

a) obj.set_score(10)
b) obj.score = 10
c) obj.score(10)
d) obj.assign('score', 10)
Correct Answer: b) obj.score = 10
Explanation:
Assigning a value to a property attribute automatically triggers its defined setter function.

23. What is composition in object-oriented programming?

a) Building complex classes by combining objects of other classes as components
b) Writing code in musical notation
c) Inheriting from multiple parent classes simultaneously
d) Translating source code to bytecode
Correct Answer: a) Building complex classes by combining objects of other classes as components
Explanation:
Composition models a 'has-a' relationship where a class contains instances of other classes as member variables.

24. What is polymorphism primarily concerned with in Python?

a) Changing object memory layout at runtime
b) Using a unified interface for different underlying data types or classes
c) Multiple inheritance resolution
d) Harkening back to compiled languages
Correct Answer: b) Using a unified interface for different underlying data types or classes
Explanation:
Polymorphism allows different types of objects to be handled through the same uniform interface.

25. Which special method is used to make an object callable like a regular function?

a) __run__
b) __call__
c) __invoke__
d) __execute__
Correct Answer: b) __call__
Explanation:
Implementing the __call__ method allows instances of a class to be invoked directly using parentheses like a function.

26. What is the primary purpose of a metaclass in Python?

a) To create classes, acting as a 'class of a class'
b) To manage instance attributes
c) To optimize loop performance
d) To handle network connections
Correct Answer: a) To create classes, acting as a 'class of a class'
Explanation:
A metaclass defines how classes themselves are constructed, intercepting class creation.

27. What is the default metaclass for all standard Python classes?

a) object
b) type
c) meta
d) super
Correct Answer: b) type
Explanation:
The default metaclass in Python is 'type'.

28. Which special method is used to customize attribute lookup when an attribute does not exist?

a) __getattribute__
b) __getattr__
c) __lookup__
d) __find__
Correct Answer: b) __getattr__
Explanation:
The __getattr__ method is invoked only when standard attribute lookup fails (attribute is missing).

29. Which special method allows custom behavior whenever *any* attribute is accessed, regardless of whether it exists?

a) __getattribute__
b) __getattr__
c) __access__
d) __fetch__
Correct Answer: a) __getattribute__
Explanation:
The __getattribute__ method intercepts every single attribute access attempt on an instance.

30. What is the purpose of the __slots__ attribute in a Python class?

a) To organize method sorting order
b) To explicitly declare data members and optimize memory by disabling per-instance __dict__ dictionaries
c) To create thread-safe locks
d) To manage database table schemas
Correct Answer: b) To explicitly declare data members and optimize memory by disabling per-instance __dict__ dictionaries
Explanation:
Using __slots__ prevents the creation of per-instance __dict__ dictionaries, significantly reducing memory overhead for classes with many instances.

31. Can a class with __slots__ defined still have a standard __dict__ attribute?

a) No, never
b) Yes, if '__dict__' is explicitly included in the __slots__ tuple
c) Yes, automatically
d) Only if inherited from a parent class
Correct Answer: b) Yes, if '__dict__' is explicitly included in the __slots__ tuple
Explanation:
You can include '__dict__' inside __slots__ if you want slot optimization alongside dynamic attribute support.

32. Which special method handles setting an attribute value?

a) __set__
b) __setattr__
c) __assign__
d) __put__
Correct Answer: b) __setattr__
Explanation:
The __setattr__ special method is called whenever an attribute assignment is attempted.

33. Which special method handles deleting an attribute using the 'del' statement?

a) __del__
b) __remove__
c) __delattr__
d) __clear__
Correct Answer: c) __delattr__
Explanation:
The __delattr__ method is invoked when an attribute deletion is requested via 'del obj.attr'.

34. What is data abstraction?

a) Exposing all internal implementation details to the user
b) Hiding complex implementation details and showing only essential features to the user
c) Converting code into abstract syntax trees
d) Drawing UML diagrams
Correct Answer: b) Hiding complex implementation details and showing only essential features to the user
Explanation:
Data abstraction focuses on exposing a simplified interface while concealing internal complexity.

35. Which special method defines context manager behavior for use with the 'with' statement?

a) __context__
b) __enter__ and __exit__
c) __with__
d) __block__
Correct Answer: b) __enter__ and __exit__
Explanation:
A context manager requires implementing both the __enter__ and __exit__ special methods.

36. What is the return value of the __enter__ method typically assigned to after the 'as' keyword in a 'with' statement?

a) The context manager instance itself or a resource proxy
b) True or False
c) An integer error code
d) None
Correct Answer: a) The context manager instance itself or a resource proxy
Explanation:
Whatever __enter__ returns is bound to the variable specified after the 'as' clause in the 'with' statement.

37. What parameters does the __exit__ method receive to handle exceptions raised inside a 'with' block?

a) exc_type, exc_val, exc_tb
b) exception, message, traceback
c) err_code, err_msg
d) No parameters
Correct Answer: a) exc_type, exc_val, exc_tb
Explanation:
The __exit__ method receives the exception type, exception value, and traceback object if an exception occurs.

38. How do you signal that an exception inside a 'with' block should be suppressed by a context manager's __exit__ method?

a) Return False
b) Return a true value (such as True)
c) Raise a new exception
d) Call context.suppress()
Correct Answer: b) Return a true value (such as True)
Explanation:
Returning a true value from __exit__ suppresses any exception that occurred inside the 'with' block.

39. Which of the following describes a class attribute?

a) An attribute shared across all instances of a class
b) An attribute unique to each individual object instance
c) An attribute stored inside local function scopes
d) An attribute that cannot be accessed outside methods
Correct Answer: a) An attribute shared across all instances of a class
Explanation:
Class attributes belong to the class itself and are shared among all instances.

40. How do instance attributes differ from class attributes?

a) Instance attributes are unique to each object instance, whereas class attributes are shared
b) Instance attributes are immutable
c) Class attributes can only be accessed via methods
d) There is no difference
Correct Answer: a) Instance attributes are unique to each object instance, whereas class attributes are shared
Explanation:
Instance attributes are bound to individual objects, while class attributes belong to the class namespace.

41. What is method overriding?

a) Defining a method in a child class with the same name as a method in its parent class to provide custom behavior
b) Calling a parent method multiple times
c) Deleting a method from a class
d) Overloading operators
Correct Answer: a) Defining a method in a child class with the same name as a method in its parent class to provide custom behavior
Explanation:
Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass.

42. Does Python support traditional method overloading (defining multiple methods with the same name and different parameters in the same class)?

a) Yes, natively
b) No, the latest definition overrides earlier ones in the same scope
c) Only in abstract classes
d) Only for magic methods
Correct Answer: b) No, the latest definition overrides earlier ones in the same scope
Explanation:
Python does not support traditional compile-time method overloading; defining multiple methods with the same name replaces the previous ones.

43. What module can be used to provide static type-checking hints and support @overload declarations for type checkers?

a) typing
b) types
c) overload
d) checker
Correct Answer: a) typing
Explanation:
The 'typing' module provides support for type hints, including the @overload decorator for static analysis tools.

44. Which special method defines equality comparison (==)?

a) __eq__
b) __equal__
c) __same__
d) __match__
Correct Answer: a) __eq__
Explanation:
The __eq__ special method defines the behavior for the equality operator (==).

45. Which special method defines inequality comparison (!=)?

a) __noteq__
b) __ne__
c) __diff__
d) __not__
Correct Answer: b) __ne__
Explanation:
The __ne__ special method implements the inequality operator (!=).

46. What feature introduced in Python 3.7 simplifies creating classes that primarily store data by automatically generating __init__, __repr__, and other methods?

a) Dataclasses (@dataclass)
b) Named tuples
c) Records
d) Structs
Correct Answer: a) Dataclasses (@dataclass)
Explanation:
The @dataclass decorator automatically generates boilerplate methods like __init__ and __repr__ for data-centric classes.

47. Which module provides the @dataclass decorator?

a) dataclasses
b) data
c) struct
d) models
Correct Answer: a) dataclasses
Explanation:
The dataclasses module supplies the @dataclass decorator and helper utilities.

48. How can you make a data class immutable (read-only instances after creation)?

a) By setting @dataclass(frozen=True)
b) By using constant variables
c) By omitting __init__
d) By setting read_only=True
Correct Answer: a) By setting @dataclass(frozen=True)
Explanation:
Setting frozen=True in the @dataclass decorator makes instances immutable, raising FrozenInstanceError on modification.

49. What is the purpose of the __post_init__ method in a dataclass?

a) To perform additional initialization logic after the auto-generated __init__ has finished
b) To clean up memory after destruction
c) To validate class syntax
d) To serialize the object
Correct Answer: a) To perform additional initialization logic after the auto-generated __init__ has finished
Explanation:
The __post_init__ method is called at the end of the auto-generated __init__ function for extra initialization or validation.

50. Which special method is used to implement hashing for objects so they can be used as dictionary keys or set elements?

a) __hash__
b) __code__
c) __key__
d) __id__
Correct Answer: a) __hash__
Explanation:
The __hash__ method returns an integer hash value, enabling objects to be stored in hash-based collections like sets and dictionaries.

51. If a class defines an __eq__ method but does not explicitly define __hash__, what happens to its hashability by default in Python 3?

a) It remains hashable using memory address
b) It becomes unhashable (.__hash__ is set to None)
c) It automatically generates a hash based on attributes
d) It raises a SyntaxError
Correct Answer: b) It becomes unhashable (.__hash__ is set to None)
Explanation:
Defining __eq__ without __hash__ implicitly sets __hash__ to None, making instances unhashable to preserve consistency.

52. Which special method defines custom behavior for the 'in' operator (__contains__)?

a) __in__
b) __contains__
c) __has__
d) __inside__
Correct Answer: b) __contains__
Explanation:
The __contains__ method implements membership test operators like 'item in container'.

53. Which special method is used to retrieve an item by index or key (e.g., obj[key])?

a) __get__
b) __getitem__
c) __index__
d) __fetch__
Correct Answer: b) __getitem__
Explanation:
The __getitem__ method enables indexing and slicing support on container objects.

54. Which special method is used to assign an item by index or key (e.g., obj[key] = value)?

a) __setitem__
b) __assign__
c) __put__
d) __setItem__
Correct Answer: a) __setitem__
Explanation:
The __setitem__ method supports item assignment via bracket notation.

55. Which special method is used to delete an item by index or key (e.g., del obj[key])?

a) __del__
b) __delitem__
c) __remove__
d) __clear__
Correct Answer: b) __delitem__
Explanation:
The __delitem__ method handles item deletion via bracket notation.

56. What is a mixin class?

a) A class designed to provide a specific set of methods for multiple inheritance without being a standalone base class
b) A class that mixes different data types
c) An abstract class with no methods
d) A class used exclusively for unit testing
Correct Answer: a) A class designed to provide a specific set of methods for multiple inheritance without being a standalone base class
Explanation:
A mixin provides specialized functionality to be inherited by other classes through composition or multiple inheritance.

57. What is the Diamond Problem in multiple inheritance?

a) An ambiguity that arises when two parent classes inherit from a common grandparent class, causing confusion over which parent's method to inherit
b) A memory leak caused by circular references
c) A syntax error in diamond-shaped code blocks
d) An issue with jeweler applications
Correct Answer: a) An ambiguity that arises when two parent classes inherit from a common grandparent class, causing confusion over which parent's method to inherit
Explanation:
The diamond problem occurs in multiple inheritance hierarchies when a class inherits from two classes that share a common base.

58. How does Python solve the Diamond Problem?

a) By prohibiting multiple inheritance entirely
b) Using C3 Linearization to produce a deterministic Method Resolution Order (MRO)
c) By picking a parent at random
d) By forcing manual method overriding
Correct Answer: b) Using C3 Linearization to produce a deterministic Method Resolution Order (MRO)
Explanation:
Python resolves the diamond problem gracefully via C3 linearization, establishing a predictable MRO.

59. What is interface inheritance (or subtyping)?

a) Inheriting method signatures and specifications without necessarily inheriting implementation code
b) Inheriting GUI components
c) Inheriting all variable values
d) Sharing private attributes
Correct Answer: a) Inheriting method signatures and specifications without necessarily inheriting implementation code
Explanation:
Interface inheritance defines what methods a subclass must implement, often realized via Abstract Base Classes.

60. What is implementation inheritance?

a) Inheriting both method signatures and their concrete implementations from a base class
b) Writing code without inheritance
c) Inheriting only abstract methods
d) Dynamic method injection
Correct Answer: a) Inheriting both method signatures and their concrete implementations from a base class
Explanation:
Implementation inheritance reuses ready-made method logic from parent classes.

61. Which built-in function returns an iterator over the attributes of an object or module?

a) dir()
b) vars()
c) attributes()
d) inspect()
Correct Answer: a) dir()
Explanation:
The dir() function returns a list of valid attributes for an object.

62. Which built-in function returns the __dict__ attribute dictionary of an object containing its writable attributes?

a) vars()
b) dict()
c) locals()
d) attributes()
Correct Answer: a) vars()
Explanation:
The vars() function returns the __dict__ attribute dictionary of an object.

63. What is an inner class (nested class) in Python?

a) A class defined inside another class body
b) A class defined inside a function
c) A private method
d) A subclass
Correct Answer: a) A class defined inside another class body
Explanation:
An inner class is a class defined within the scope of another enclosing class.

64. Can an inner class in Python be instantiated independently of the outer class?

a) Yes, depending on how it's referenced
b) No, never
c) Only inside outer class methods
d) Only with metaclasses
Correct Answer: a) Yes, depending on how it's referenced
Explanation:
Unlike Java, Python inner classes are not automatically tied to an outer instance, so they can be instantiated directly via Outer.Inner().

65. What is monkey patching in Python?

a) Dynamic modification of a class or module at runtime
b) Fixing bugs using automated scripts
c) Writing unit tests for primates
d) Rewriting bytecode
Correct Answer: a) Dynamic modification of a class or module at runtime
Explanation:
Monkey patching refers to dynamically altering or extending classes or modules at runtime without changing original source code files.

66. Which special method defines how an object is converted to a boolean value (for truthiness evaluation)?

a) __bool__
b) __truth__
c) __cond__
d) __check__
Correct Answer: a) __bool__
Explanation:
The __bool__ special method customizes truth value testing (if obj:); falls back to __len__ if absent.

67. What is delegation in object-oriented design?

a) An object handling a request by delegating responsibility to a helper or composed object
b) Delegating tasks to different CPU threads
c) Inheriting all parent methods
d) Overriding methods
Correct Answer: a: An object handling a request by delegating responsibility to a helper or composed object
Explanation:
Delegation is a design pattern where an object forwards requests to another helper object to perform tasks.

68. What is the primary benefit of using getters and setters (encapsulation)?

a) Controlling access and validation when reading or writing internal attributes
b) Speeding up execution time
c) Reducing memory usage
d) Eliminating the need for __init__
Correct Answer: a) Controlling access and validation when reading or writing internal attributes
Explanation:
Getters and setters allow you to intercept, validate, or transform attribute access safely.

69. What is a descriptor in Python?

a) An object that implements at least one of __get__, __set__, or __delete__
b) A string describing a class
c) A type hint decorator
d) A docstring
Correct Answer: a) An object that implements at least one of __get__, __set__, or __delete__
Explanation:
Descriptors control attribute access for other classes when stored as class attributes.

70. What is the difference between a non-data descriptor and a data descriptor?

a) Data descriptors define both __get__ and __set__/__delete__; non-data descriptors define only __get__
b) Data descriptors store integers; non-data descriptors store strings
c) Data descriptors are faster
d) There is no difference
Correct Answer: a) Data descriptors define both __get__ and __set__/__delete__; non-data descriptors define only __get__
Explanation:
Data descriptors override instance dictionaries during attribute lookup, whereas non-data descriptors can be shadowed by instance attributes.

71. Are properties created with @property data or non-data descriptors?

a) Data descriptors
b) Non-data descriptors
c) Regular attributes
d) Static methods
Correct Answer: a) Data descriptors
Explanation:
Properties created using @property define both a getter and a setter, making them data descriptors.

72. Which special method is used to customize string conversion for debugging (__repr__ vs __str__)?

a) __repr__
b) __str__
c) __debug__
d) __print__
Correct Answer: a) __repr__
Explanation:
The __repr__ method provides the official, unambiguous representation meant for debugging.

73. If __str__ is not implemented by a class, what does Python fall back to when str() or print() is called?

a) __repr__
b) An empty string
c) None
d) TypeError
Correct Answer: a) __repr__
Explanation:
If __str__ is missing, Python automatically falls back to calling __repr__.

74. What is object serialization?

a) Converting an object state into a byte stream or format for storage or transmission
b) Sorting objects in an array
c) Executing objects in serial order
d) Converting objects to strings
Correct Answer: a) Converting an object state into a byte stream or format for storage or transmission
Explanation:
Serialization transforms live objects into persistent formats like JSON or bytes.

75. Which built-in Python module is commonly used for serializing arbitrary Python objects?

a) pickle
b) json
c) serialize
d) marshal
Correct Answer: a) pickle
Explanation:
The 'pickle' module serializes and deserializes arbitrary Python object structures.

76. Which special methods can be used to customize how an object is pickled?

a) __getstate__ and __setstate__
b) __pack__ and __unpack__
c) __save__ and __load__
d) __serialize__ and __deserialize__
Correct Answer: a) __getstate__ and __setstate__
Explanation:
Objects can customize their pickling behavior by implementing __getstate__ and __setstate__.

77. What is the purpose of the __copy__ and __deepcopy__ special methods?

a) To customize shallow and deep cloning behavior via copy.copy() and copy.deepcopy()
b) To duplicate files on disk
c) To back up databases
d) To clone classes
Correct Answer: a) To customize shallow and deep cloning behavior via copy.copy() and copy.deepcopy()
Explanation:
Implementing __copy__ and __deepcopy__ allows custom objects to define how they are cloned.

78. What is a static variable in Python OOP terms?

a) A class attribute shared across all instances
b) A variable inside a method
c) A constant that cannot be reassigned
d) An immutable local variable
Correct Answer: a) A class attribute shared across all instances
Explanation:
Class attributes act as static variables shared across all instances of that class.

79. Can you add new attributes to an object instance dynamically outside the class definition in standard Python?

a) Yes, unless __slots__ restricts it
b) No, never
c) Only inside methods
d) Only with metaclasses
Correct Answer: a) Yes, unless __slots__ restricts it
Explanation:
Standard Python instances store attributes in a dynamic __dict__, allowing attributes to be added at runtime.

80. What is loose coupling in object-oriented design?

a) A design approach where classes have minimal dependencies on one another
b) Classes sharing all internal data
c) Using multiple inheritance
d) Weak reference management
Correct Answer: a) A design approach where classes have minimal dependencies on one another
Explanation:
Loose coupling minimizes interdependencies, making systems more maintainable and modular.

81. What is tight coupling?

a) A design state where classes are highly dependent on each other's internal implementations
b) Proper encapsulation
c) Thread synchronization
d) Using immutable dataclasses
Correct Answer: a) A design state where classes are highly dependent on each other's internal implementations
Explanation:
Tight coupling means changes in one class force cascading changes in others, which is generally discouraged.

82. What does SOLID stand for in object-oriented design principles?

a) Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion
b) Static, Object, Logic, Inheritance, Design
c) Simple, Optimized, Linked, Integrated, Dynamic
d) Secure, Operational, Linear, Interactive, Distributed
Correct Answer: a) Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion
Explanation:
SOLID represents five core principles of robust object-oriented software design.

83. What does the Liskov Substitution Principle (LSP) state?

a) Objects of a superclass should be replaceable with objects of a subclass without breaking application correctness
b) Subclasses must override all parent methods
c) Classes must have only one parent
d) Subclasses cannot access private attributes
Correct Answer: a) Objects of a superclass should be replaceable with objects of a subclass without breaking application correctness
Explanation:
LSP ensures that derived classes extend base classes without altering expected behavioral contracts.

84. What does the Open/Closed Principle state?

a) Software entities should be open for extension, but closed for modification
b) Source code must be open source
c) Classes must be open for direct attribute modification
d) Files must be closed after reading
Correct Answer: a) Software entities should be open for extension, but closed for modification
Explanation:
The Open/Closed Principle advocates adding new functionality through inheritance or composition rather than editing existing tested code.

85. What does the Single Responsibility Principle state?

a) A class should have only one reason to change, meaning it should have responsibility over a single part of functionality
b) A class should have only one method
c) An application should have only one class
d) Methods should take a single argument
Correct Answer: a) A class should have only one reason to change, meaning it should have responsibility over a single part of functionality
Explanation:
The Single Responsibility Principle ensures each class focuses on a single job or concern.

86. What is a factory method pattern in Python?

a) A creational design pattern that uses factory methods to deal with the problem of creating objects without specifying exact classes
b) A method that manufactures hardware components
c) A function that generates random numbers
d) A class that compiles code
Correct Answer: a) A creational design pattern that uses factory methods to deal with the problem of creating objects without specifying exact classes
Explanation:
Factory methods encapsulate object creation logic, decoupling instantiation from client code.

87. What is the Singleton design pattern?

a) A design pattern that restricts a class to a single instantiation instance throughout the program
b) A class with only one method
c) A variable that holds a single value
d) A single-threaded execution model
Correct Answer: a) A design pattern that restricts a class to a single instantiation instance throughout the program
Explanation:
Singleton ensures globally accessible single-instance management.

88. Which special method is responsible for creating and returning a new instance before __init__ initializes it?

a) __new__
b) __init__
c) __create__
d) __alloc__
Correct Answer: a) __new__
Explanation:
The __new__ method is the constructor that creates and returns the new instance, whereas __init__ is merely the initializer.

89. Why would you override __new__ instead of __init__?

a) When subclassing immutable types like int or str, or implementing Singleton patterns
b) To initialize instance variables
c) To print debug messages
d) To handle string formatting
Correct Answer: a) When subclassing immutable types like int or str, or implementing Singleton patterns
Explanation:
Since immutable objects cannot be modified in __init__, __new__ must be used to customize their creation.

90. What is the adapter design pattern?

a) A structural pattern that allows objects with incompatible interfaces to collaborate
b) An electrical converter plugin
c) A method to adapt code speed
d) A type casting function
Correct Answer: a) A structural pattern that allows objects with incompatible interfaces to collaborate
Explanation:
Adapters bridge gaps between differing interfaces so disparate classes can work together.

91. What is the Observer design pattern?

a) A behavioral pattern where an object (subject) maintains a list of dependents (observers) and notifies them of state changes
b) A debugging tool to observe variables
c) A pattern for monitoring CPU usage
d) A unit testing framework
Correct Answer: a) A behavioral pattern where an object (subject) maintains a list of dependents (observers) and notifies them of state changes
Explanation:
The observer pattern establishes publish-subscribe relationships between objects.

92. What is the Strategy design pattern?

a) A behavioral pattern that enables selecting an algorithm's behavior at runtime from a family of interchangeable algorithms
b) A game strategy simulator
c) A compiler optimization technique
d) A multithreading schedule
Correct Answer: a) A behavioral pattern that enables selecting an algorithm's behavior at runtime from a family of interchangeable algorithms
Explanation:
Strategy patterns encapsulate interchangeable algorithms into separate classes.

93. How can you make a class instance completely read-only or prevent dynamic attribute additions without using __slots__?

a) By using dataclasses with frozen=True or overriding __setattr__ to raise errors
b) By making all methods static
c) By using private name mangling
d) By deleting __dict__
Correct Answer: a) By using dataclasses with frozen=True or overriding __setattr__ to raise errors
Explanation:
You can prevent attribute mutation by freezing dataclasses or intercepting assignments in __setattr__.

94. What is the output of isinstance(True, int) in Python?

a) True
b) False
c) TypeError
d) None
Correct Answer: a) True
Explanation:
In Python, bool is a subclass of int, so isinstance(True, int) evaluates to True.

95. Which special method is used to implement unary negation (e.g., -obj)?

a) __neg__
b) __inverse__
c) __minus__
d) __not__
Correct Answer: a) __neg__
Explanation:
The __neg__ special method implements unary negation (-).

96. Which special method is used to implement unary plus (e.g., +obj)?

a) __pos__
b) __plus__
c) __add__
d) __unary__
Correct Answer: a) __pos__
Explanation:
The __pos__ special method implements unary plus (+).

97. Which special method implements absolute value calculation via abs(obj)?

a) __abs__
b) __absolute__
c) __magnitude__
d) __mod__
Correct Answer: a) __abs__
Explanation:
The abs() built-in function invokes the __abs__ special method.

98. What is a protocol in Python (structural subtyping)?

a) An explicit definition of methods an object must have, checked statically via typing.Protocol
b) A network communication standard
c) A security rule
d) An abstract base class
Correct Answer: a) An explicit definition of methods an object must have, checked statically via typing.Protocol
Explanation:
Protocols enable structural subtyping (static duck typing) using typing.Protocol.

99. What is the primary difference between public, protected, and private attribute conventions in Python?

a) They are naming conventions (public has no underscore, protected has one underscore, private has double underscores triggering name mangling)
b) Python strictly enforces access permissions at runtime for all three
c) Private attributes cannot be accessed anywhere
d) Public attributes are read-only
Correct Answer: a) They are naming conventions (public has no underscore, protected has one underscore, private has double underscores triggering name mangling)
Explanation:
Python relies on programmer discipline ('we are all consenting adults here') backed by naming conventions and name mangling rather than hard access blocks.
← Previous: Python Functions MCQs
Next →: Python Strings MCQs
NewPython Control Flow MCQs

Python Control Flow MCQs

Control flow statements regulate the order in which individual code statements are evaluated and executed in a Python program. Python…

By MCQs Generator
Newpython variables & datatypes MCQs

Python Variables & Data Types MCQs

Variables in Python act as dynamic references reserved in memory to store objects, operating without explicit data type declarations due…

By MCQs Generator
NewLatest Python Operators MCQs

Latest Python Operators MCQs

Operators in Python are special symbols and keywords used to manipulate data, perform mathematical computations, make boolean comparisons, and control…

By MCQs Generator