Courseiva

CCNA Advanced Object Oriented Programming Questions

52 questions · Advanced Object Oriented Programming · All types, answers revealed

1
MCQeasy

Which of the following describes the purpose of the __slots__ attribute in a class?

A.To allow private attribute access.
B.To define the method resolution order.
C.To improve performance and reduce memory usage.
D.To prevent inheritance.
AnswerC

This is the primary design goal of __slots__.

Why this answer

__slots__ restricts the creation of new instance attributes and reduces memory footprint by preventing the creation of a per-instance __dict__.

2
MCQhard

What happens if you use a decorator on a class that returns a modified version of the class?

A.The original class object is replaced.
B.It triggers a SyntaxError.
C.The class cannot be instantiated.
D.The metaclass is ignored.
AnswerA

The variable name points to the returned object, not the original class definition.

Why this answer

The class name, module, and other attributes might be replaced, which can confuse introspection tools; functools.wraps is usually not applicable to classes.

3
MCQeasy

Which magic method is responsible for providing the informal string representation of an object, typically used for user-facing output?

A.__str__
B.__format__
C.__unicode__
D.__repr__
AnswerA

__str__ is the standard method for informal string conversion.

Why this answer

The __str__ method is used for informal, readable string representations, whereas __repr__ is for formal, unambiguous representations.

4
MCQmedium

Which magic method allows an object to behave like a function?

A.__apply__
B.__invoke__
C.__func__
D.__call__
AnswerD

This is the correct magic method for function-like objects.

Why this answer

The __call__ method enables an object to be invoked with parentheses syntax.

5
MCQhard

In the context of the Descriptor Protocol, what is the primary difference between a data descriptor and a non-data descriptor?

A.Non-data descriptors can override instance dictionary lookup.
B.Data descriptors define __set__ or __delete__, whereas non-data descriptors do not.
C.Data descriptors only function with class attributes.
D.Non-data descriptors are always read-only.
AnswerB

This is the strict definition of the descriptor protocol's precedence.

Why this answer

A data descriptor defines both __get__ and __set__ (or __delete__), while a non-data descriptor only defines __get__.

6
MCQmedium

In the Factory pattern, what should you do if the requested type is unknown?

A.Log the error and return the base class.
B.Raise a ValueError.
C.Return a default instance.
D.Return None.
AnswerB

Explicitly signaling an error is best practice.

Why this answer

Raising a ValueError or a custom 'UnknownTypeException' is the standard way to handle invalid inputs in a factory.

7
MCQmedium

What is the difference between a class-level variable and an instance-level variable?

A.Instance-level variables cannot be modified.
B.Class-level variables are always constant.
C.Class-level variables are hidden from subclasses.
D.Class-level variables are shared by all instances.
AnswerD

Modifying a class variable affects all instances.

Why this answer

A class-level variable is shared across all instances of the class, whereas an instance-level variable is specific to each object.

8
MCQmedium

When overriding the __getattr__ method, what must you be careful to avoid?

A.Infinite recursion by accessing non-existent attributes.
B.Raising AttributeError.
C.Accessing class attributes.
D.Calling super().__getattr__.
AnswerA

Always use super() or direct dictionary access to avoid the cycle.

Why this answer

Infinite recursion occurs if you try to access an attribute inside __getattr__ that does not exist, triggering __getattr__ again.

9
MCQmedium

When using a metaclass, how can you access the class attributes during the class definition?

A.By calling super().
B.By accessing the class __dict__.
C.By querying the base class.
D.By accessing the namespace dictionary passed to __new__.
AnswerD

The dictionary is the source of all definitions.

Why this answer

The class dictionary passed to the metaclass's __new__ method contains all the attributes defined within the class body.

10
Multi-Selectmedium

Which TWO of the following are true regarding multiple inheritance in Python?

Select 2 answers
A.It is not supported.
B.super() is used for cooperative method calls.
C.The MRO is determined at runtime.
D.It uses the C3 linearization algorithm.
E.Multiple inheritance is always preferred over composition.
AnswersB, D

This allows all classes in the chain to execute.

Why this answer

Python uses C3 MRO to resolve calls, and super() is used for cooperative calls.

11
Multi-Selecthard

Which THREE of the following statements are correct about Python metaclasses?

Select 3 answers
A.They are instances of 'type'.
B.They are strictly for private attribute management.
C.They only apply to the class itself, not its subclasses.
D.They modify the class creation process.
E.They are used to implement the Singleton pattern.
AnswersA, D, E

All classes are types.

Why this answer

Metaclasses create classes, they can be inherited, and they can be used for automatic registration.

12
MCQhard

What is the primary risk of using 'getattr' without a default value?

A.It returns None.
B.It enters an infinite loop.
C.It raises an AttributeError.
D.It creates the attribute.
AnswerC

This is the standard behavior when the attribute is missing.

Why this answer

If the attribute is not found, it raises an AttributeError, potentially crashing the application if not handled.

13
MCQmedium

When using the __call__ method to implement a decorator, what does the decorator receive as an argument?

A.The arguments to the function.
B.The instance of the class.
C.The class object.
D.The function to be decorated.
AnswerD

The decorator captures the function object.

Why this answer

The decorator receives the function object that is being decorated as the argument to the constructor (if the decorator is a class instance) or directly if it is a function.

14
MCQhard

Why does the __init__ method not return anything?

A.Because it is designed to initialize an existing instance.
B.Because of internal Python constraints.
C.To allow for multiple initialization.
D.Because it's a generator.
AnswerA

The instance is already created by __new__.

Why this answer

The __init__ method is for initialization only; the object creation is handled by __new__.

15
MCQhard

What is the purpose of the 'weakref' module in relation to the Observer pattern?

A.To allow private access to observers.
B.To ensure thread safety.
C.To prevent memory leaks.
D.To serialize observers.
AnswerC

Weak references do not increment the reference count, allowing collection.

Why this answer

It allows the subject to maintain references to observers without preventing their collection by the garbage collector.

16
MCQhard

How do you define a property in a class to make it read-only?

A.Use the 'readonly' decorator.
B.Use the 'final' modifier.
C.Set the attribute to private.
D.Define a property with only @property, no @setter.
AnswerD

This creates a read-only attribute interface.

Why this answer

By defining the property with only a getter (using @property) and omitting the setter method.

17
MCQeasy

Which magic method is used to control how an instance is displayed when using the print() function?

A.__str__
B.__display__
C.__repr__
D.__print__
AnswerA

This is the primary method for string conversion.

Why this answer

print() implicitly calls str(obj), which in turn calls __str__.

18
Multi-Selecthard

Which THREE of the following are true about the Python descriptor protocol?

Select 3 answers
A.Non-data descriptors can define __set__.
B.They only work for instance attributes.
C.They must be defined in the class body.
D.Data descriptors take precedence over instance __dict__.
E.They are the mechanism behind @property.
AnswersC, D, E

Descriptors are class attributes.

Why this answer

Descriptors allow you to manage attribute access, they have specific lookup order, and they are used by property/classmethod internally.

19
MCQmedium

In the context of the Observer pattern, what is the benefit of an event-driven system over a direct-method-call approach?

A.Reduced memory usage.
B.Increased performance.
C.Decoupling between the subject and observers.
D.Automatic thread synchronization.
AnswerC

The subject maintains a generic interface for observers.

Why this answer

Decoupling is the primary benefit; the subject does not need to know the implementation details of the observers.

20
MCQhard

What is the purpose of the __set_name__ method in descriptors?

A.To set the name of the class.
B.To delete the attribute.
C.To rename the attribute.
D.To allow the descriptor to know its name in the owner class.
AnswerD

This is the purpose of the method.

Why this answer

__set_name__ is called at class creation time to inform the descriptor of its name in the owner class, allowing it to store values in a private attribute without needing to know the name beforehand.

21
MCQmedium

Why should you use super() instead of calling the parent class method directly by name?

A.It is required for private methods.
B.It correctly resolves the next method in the MRO.
C.It is faster.
D.It makes the code more verbose.
AnswerB

This is the correct architectural use of super().

Why this answer

super() respects the MRO and allows for cooperative multiple inheritance, whereas hard-coding the class name breaks if the hierarchy is modified.

22
MCQmedium

What is the purpose of the 'type' function when called with three arguments?

A.To register a class.
B.To create a new class dynamically.
C.To inherit from multiple classes.
D.To check object type.
AnswerB

The three-argument form is the type constructor for classes.

Why this answer

It is used for dynamic class creation: type(name, bases, dict).

23
MCQmedium

What does the @abstractmethod decorator do when applied to a method inside an ABC?

A.It requires the subclass to implement the method.
B.It prevents the method from being called.
C.It automatically generates a default implementation.
D.It makes the method faster.
AnswerA

This is the core requirement of ABCs.

Why this answer

It marks the method as requiring an override in any non-abstract concrete subclass.

24
MCQmedium

When using abstract base classes (ABCs) from the abc module, what happens if a class inherits from an ABC but fails to implement one of the abstract methods?

A.The class will be created, but calling the missing method will raise an AttributeError.
B.The class will be marked as abstract and will raise a TypeError upon instantiation.
C.The missing method will default to a 'pass' statement.
D.The parent ABC will automatically provide a NotImplementedError.
AnswerB

This is the core behavior of ABCs; they act as templates that must be fully realized.

Why this answer

Python will raise a TypeError when you attempt to instantiate the class, preventing the creation of an incomplete object.

25
MCQmedium

You are implementing a Singleton pattern using the __new__ method. Why is it considered best practice to also define a __call__ method in the metaclass or use a decorator instead of just overriding __new__ in the base class?

A.It prevents the creation of multiple instances during the unpickling process.
B.The __new__ method cannot accept variable arguments in Python 3.
C.The __new__ method is reserved for static methods only.
D.It is required for thread-safe access to the instance variable.
AnswerA

Using a metaclass or a decorator ensures that the instance returned during deserialization is the same one already created, maintaining the Singleton property.

Why this answer

Overriding __new__ in a base class can lead to issues with pickling and deserialization, as __new__ is called every time an object is unpickled, potentially creating multiple instances.

26
MCQmedium

What is the consequence of not calling super().__init__() in a class with multiple inheritance?

A.The class will not be created.
B.All attributes will be lost.
C.The initialization chain for parent classes is interrupted.
D.Python will raise a RuntimeError.
AnswerC

Cooperative multiple inheritance depends on every class calling super().

Why this answer

The MRO chain will break, and sibling classes may not be initialized properly, potentially causing missing attributes or logic errors.

27
MCQeasy

Which magic method is triggered when an object is deleted using the 'del' keyword?

A.__clear__
B.__del__
C.__remove__
D.__destroy__
AnswerB

This is the finalizer method.

Why this answer

The __del__ method is called when the object's reference count reaches zero.

28
MCQhard

What is the result of applying the @staticmethod decorator to a method inside a class that also defines a metaclass?

A.The metaclass must manually convert it back to a static method.
B.It raises a TypeError at class definition time.
C.The method is correctly bound as a static function regardless of the metaclass.
D.The metaclass will treat the method as an instance method.
AnswerC

The descriptor logic for @staticmethod operates independently of the class-level metaclass definition.

Why this answer

The @staticmethod decorator creates a static method object which is stored in the class dictionary; it is independent of the metaclass's __init__ logic for instance methods.

29
MCQhard

What is the effect of setting __slots__ in a parent class on a child class that does not define its own __slots__?

A.The child class will have a __dict__ attribute, overriding the parent's optimization.
B.The child class will raise an error at instantiation.
C.The child class will inherit the memory savings automatically.
D.The child class will be unable to add new attributes.
AnswerA

By default, subclasses receive a __dict__.

Why this answer

The child class will receive an instance __dict__ unless it also defines __slots__, effectively defeating the memory optimization of the parent.

30
Multi-Selecthard

Which THREE of the following are potential pitfalls of the Singleton pattern in Python?

Select 3 answers
A.They cannot be used with inheritance.
B.They introduce global state.
C.They cause difficulties in dependency injection.
D.They make unit testing more difficult.
E.They are always thread-safe.
AnswersB, C, D

Singletons are global by definition.

Why this answer

Singletons can be hard to test, cause hidden global state, and create difficulties in multi-threaded environments.

31
MCQmedium

How do you implement the 'Strategy' pattern in Python?

A.By using a large switch-case statement.
B.By creating a metaclass for all strategies.
C.By passing strategy instances into the context constructor.
D.By using inheritance for every strategy.
AnswerC

Dependency injection is a key part of the Strategy pattern.

Why this answer

By injecting different strategy objects into a context class, which then delegates operations to the injected object.

32
MCQmedium

When designing a class hierarchy, what is the best way to prevent a method from being overridden by subclasses?

A.Defining it as a private method.
B.Defining it as a static method.
C.Using the @final decorator from typing.
D.Using the 'final' keyword.
AnswerC

The @final decorator is the standard way to indicate that a method should not be overridden.

Why this answer

Python does not have a native 'final' keyword, but naming conventions (e.g., __method) or raising errors in the subclass can be used, though it is often discouraged in favor of clear documentation.

33
MCQmedium

How do you correctly call a method from a sibling class in a diamond inheritance structure using super()?

A.Call the grandparent class directly.
B.Use super() in each class to delegate to the next class in the MRO.
C.Use the __bases__ attribute to iterate through parents.
D.Explicitly call the sibling class method by name.
AnswerB

super() ensures that each class in the MRO is initialized exactly once.

Why this answer

super() follows the Method Resolution Order (MRO), which correctly handles diamond inheritance by delegating calls to the next class in the chain, not just the parent.

34
Multi-Selectmedium

Which TWO of the following are correct regarding the 'with' statement in Python?

Select 2 answers
A.It works by implicit __init__ calling.
B.It only works with file objects.
C.It can be used with any object.
D.It requires the class to define __enter__ and __exit__.
E.It guarantees that __exit__ is called even if an exception occurs.
AnswersD, E

These are the mandatory methods.

Why this answer

The 'with' statement handles setup and teardown, and it requires both __enter__ and __exit__.

35
MCQmedium

In the context of the Factory pattern, what does a concrete factory implement?

A.The registration logic for all factories.
B.The creation interface for specific product variants.
C.The logic for the singleton pattern.
D.The product logic.
AnswerB

This is the essence of a concrete factory.

Why this answer

A concrete factory implements the interface defined by the abstract factory to produce specific products.

36
MCQmedium

When implementing the Singleton pattern, what is the advantage of using a module-level instance over a class-based Singleton?

A.It is more secure.
B.It allows multiple instances if needed.
C.It is simpler and leverages Python's built-in module caching mechanism.
D.It supports lazy loading.
AnswerC

Modules are cached in sys.modules, making them thread-safe and singular by design.

Why this answer

Python modules are naturally Singletons because they are initialized only once upon the first import.

37
MCQeasy

What is the purpose of the __repr__ method?

A.To be called by print().
B.User-friendly output.
C.To store the object in memory.
D.Unambiguous representation for debugging.
AnswerD

This is the intended goal of __repr__.

Why this answer

It provides a formal, unambiguous string representation of an object, ideally suitable for re-creating the object.

38
MCQhard

Why does the 'abc' module provide the 'ABCMeta' metaclass?

A.To allow private methods.
B.To improve method resolution speed.
C.To enforce abstract method implementation at instantiation.
D.To support multiple inheritance.
AnswerC

This is the core purpose of ABCMeta.

Why this answer

ABCMeta is the metaclass that implements the logic to prevent instantiation of classes with abstract methods.

39
Multi-Selecthard

Which THREE of the following represent common issues when using __slots__?

Select 3 answers
A.Subclasses must define their own __slots__ to avoid creating a __dict__.
B.They make it impossible to add new attributes dynamically.
C.They are incompatible with all decorators.
D.They prevent the use of multiple inheritance.
E.Classes with __slots__ cannot have a __dict__ by default.
AnswersA, B, E

Otherwise, the child gets a dictionary.

Why this answer

Slots can break pickling in some cases, make multiple inheritance tricky, and prevent adding attributes dynamically.

40
MCQmedium

You are implementing the Observer pattern. Why should you avoid using a strong reference to the observers in the subject's list?

A.It causes circular dependency issues.
B.It makes the notify method thread-unsafe.
C.It violates the principle of encapsulation.
D.It prevents the observer from being garbage collected when it is no longer needed.
AnswerD

Weak references allow the garbage collector to reclaim the observer even if it's in the subject's list.

Why this answer

Strong references prevent garbage collection of the observers, leading to memory leaks if observers are meant to be temporary.

41
MCQeasy

What is the primary difference between @classmethod and @staticmethod?

A.@staticmethod can access instance variables.
B.@classmethod receives the class as the first argument; @staticmethod does not.
C.@classmethod is for private methods.
D.@classmethod is slower.
AnswerB

This is the fundamental distinction.

Why this answer

@classmethod receives the class as the first argument, while @staticmethod receives no implicit class or instance argument.

42
MCQeasy

Which magic method enables index access (e.g., obj[i])?

A.__getitem__
B.__index__
C.__setitem__
D.__access__
AnswerA

This is for retrieval.

Why this answer

The __getitem__ method allows an object to support indexing.

43
Multi-Selectmedium

Which TWO of the following are true about magic methods?

Select 2 answers
A.They are only available for built-in types.
B.They provide hooks into Python language operators.
C.They always start and end with '__'.
D.They cannot be overridden.
E.They are intended for direct calling by the user.
AnswersB, C

They are the standard hooks for operators like +, -, etc.

Why this answer

Magic methods start and end with double underscores, and they allow objects to integrate with Python's built-in syntax.

44
Multi-Selectmedium

Which TWO of the following are valid ways to create a singleton in Python?

Select 2 answers
A.Using a global variable that is not initialized.
B.Using a function that returns a new instance every call.
C.Using a base class with a custom __new__ method.
D.Using a standard class without any special methods.
E.Using a module as a singleton.
AnswersC, E

Can be used, though metaclasses are cleaner.

Why this answer

Modules are natural singletons, and metaclasses can be used to control instance creation.

45
MCQeasy

What happens when you add two objects of a class that implements __add__?

A.It does nothing.
B.It concatenates the objects.
C.It raises a TypeError.
D.The __add__ method is called.
AnswerD

This is how operator overloading works.

Why this answer

The __add__ method is automatically called by the interpreter when the '+' operator is used.

46
MCQhard

If you define a class with a metaclass that has a custom __call__ method, when is that __call__ method executed?

A.Every time an instance method is called.
B.When an instance of the class is created.
C.When the metaclass is first imported.
D.When the class itself is defined.
AnswerB

Metaclass __call__ intercepts the instantiation of its class objects.

Why this answer

The metaclass's __call__ method is invoked whenever the class created by that metaclass is instantiated (i.e., when you call the class name like MyClass()).

47
MCQeasy

Which method is used to customize the behavior of the 'in' operator?

A.__contains__
B.__has__
C.__find__
D.__in__
AnswerA

This is the correct magic method.

Why this answer

The __contains__ method is called when using the 'in' or 'not in' operators.

48
MCQeasy

Which magic method should you implement to make your objects support the 'with' statement context manager?

A.__context__
B.__enter__ and __exit__
C.__open__ and __close__
D.__init__ and __del__
AnswerB

These are the mandatory methods for the context manager protocol.

Why this answer

The __enter__ and __exit__ methods are required to implement the context manager protocol.

49
MCQeasy

Which function is used to check if an object is an instance of a class?

A.hasattr()
B.issubclass()
C.type()
D.isinstance()
AnswerD

This handles inheritance correctly.

Why this answer

isinstance(obj, Class) is the standard way to check inheritance.

50
MCQmedium

In the context of the Factory pattern in Python, what is a typical benefit of using a registry-based approach instead of a large if-else block?

A.It guarantees thread safety without locks.
B.It prevents the instantiation of abstract classes.
C.It enables easy extension by adding new products without changing the factory.
D.It significantly reduces memory usage.
AnswerC

This is the open/closed principle in action.

Why this answer

Registry-based factories allow for decoupled code where new classes can be registered without modifying the factory's core logic.

51
MCQhard

Consider a class that uses a metaclass to automatically register subclasses in a dictionary. If you want to prevent the base class itself from being registered, how should the metaclass be implemented?

A.Check the class name within the metaclass __init__ method before adding it to the registry.
B.Use the __call__ method to raise a TypeError if the base class is instantiated.
C.Set the __new__ method of the metaclass to return None if the name is 'Base'.
D.Define a decorator on the base class that removes it from the metaclass registry.
AnswerA

The __init__ method is invoked after the class creation, allowing you to filter out the base class based on attributes or names.

Why this answer

The metaclass __init__ method receives the class object. By checking the class name or using a specific attribute (e.g., _is_base), you can conditionally skip registration.

52
MCQhard

Why might you use the __init_subclass__ hook instead of a metaclass?

A.Metaclasses are deprecated.
B.Metaclasses cannot be used for registration.
C.It is faster at runtime.
D.It is easier to implement and avoids metaclass conflicts.
AnswerD

Metaclass conflicts arise when multiple classes have different metaclasses; __init_subclass__ avoids this.

Why this answer

__init_subclass__ provides a simpler way to perform logic when a subclass is created, without the complexity and inheritance issues associated with custom metaclasses.

Ready to test yourself?

Try a timed practice session using only Advanced Object Oriented Programming questions.