Courseiva

CCNA Advanced Oop And Performance Questions

32 questions · Advanced Oop And Performance topic · All types, answers revealed

1
MCQhard

You are utilizing abstract base classes (ABCs). How do you enforce that a subclass implements a specific method?

A.Use a metaclass check
B.Use the @abstractmethod decorator
C.Raise NotImplementedError in the base class
D.Pass the method name to __init__
AnswerB

@abstractmethod ensures the subclass cannot be instantiated without overriding the method.

Why this answer

The @abstractmethod decorator marks a method as requiring implementation in concrete subclasses.

2
MCQhard

You need to prevent an object's attribute from being modified after it is set. Which approach provides the most robust implementation?

A.Using a class attribute instead of instance attribute
B.Using a @property decorator with no setter
C.Overriding __setattr__ to disallow modification
D.Setting the attribute to private using double underscores
AnswerB

A @property without a @name.setter makes the attribute read-only.

Why this answer

A property with only a getter (or a custom setter that raises an exception) effectively creates a read-only attribute.

3
MCQmedium

You have an object that behaves like a function. Which magic method must be implemented to make this possible?

A.__call__
B.__apply__
C.__invoke__
D.__function__
AnswerA

__call__ turns an object into a callable.

Why this answer

The __call__ method allows an object instance to be invoked as a function.

4
MCQeasy

You need to ensure that a class can only be instantiated once throughout the application lifecycle. Which design pattern is most appropriate?

A.Factory Pattern
B.Adapter Pattern
C.Proxy Pattern
D.Singleton Pattern
AnswerD

Singleton restricts instantiation to a single object.

Why this answer

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

5
MCQeasy

When managing resources like file handles, what is the best practice to ensure they are always closed?

A.Using a context manager (with statement)
B.Manually calling .close()
C.Relying on garbage collection
D.Using a try-finally block
AnswerA

The with statement guarantees resource release.

Why this answer

The with statement (context manager) ensures that cleanup code is executed regardless of exceptions.

6
MCQmedium

When using inheritance, how can you explicitly call a method from a specific parent class that is not the immediate superclass?

A.self.method()
B.BaseClass.method(self)
C.Using the __parent__ attribute
D.super().method()
AnswerB

Direct invocation on the class bypasses the MRO.

Why this answer

Calling the method directly on the class object (e.g., Parent.method(self)) bypasses the MRO.

7
MCQhard

You need to implement a custom class that behaves like a sequence, allowing indexing and length checking. Which magic methods are required?

A.__iter__ and __next__
B.__index__ and __size__
C.__setitem__ and __delitem__
D.__getitem__ and __len__
AnswerD

These two methods allow indexing and length retrieval.

Why this answer

To be a sequence, a class needs to implement __getitem__ and __len__.

8
MCQhard

In a multi-threaded application, you need to ensure that shared state is modified safely. Which tool is the most appropriate for this task?

A.time.sleep
B.sys.settrace
C.threading.Lock
D.gc.collect
AnswerC

Locks provide mutual exclusion to prevent race conditions.

Why this answer

The threading.Lock primitive allows only one thread to access a resource at a time.

9
MCQhard

When writing a metaclass, what is the 'cls' parameter in the __new__ method referring to?

A.The instance of the class
B.The class being created
C.The parent class
D.The metaclass itself
AnswerD

The first argument to __new__ in a metaclass is the metaclass type.

Why this answer

In a metaclass's __new__ method, 'cls' refers to the metaclass itself, not the class being created.

10
Multi-Selecthard

Which THREE of the following are features of the 'threading' module in Python?

Select 3 answers
A.Shared memory between different processes
B.Semaphore objects
C.Lock synchronization primitives
D.Event objects for signaling
E.Automatic global interpreter lock removal
AnswersB, C, D

Semaphores are supported for resource counting.

Why this answer

The threading module provides Locks, Semaphores, and Events for synchronization.

11
MCQeasy

Which operator is used to perform bitwise AND operations?

A.&&
B.&
C.^
D.|
AnswerB

& performs bitwise AND.

Why this answer

The & operator is the bitwise AND operator in Python.

12
MCQmedium

You are handling large datasets and want to improve memory efficiency. Which Python feature allows you to iterate over a large sequence without loading it entirely into memory?

A.Generators
B.Deepcopy
C.Set literals
D.List comprehensions
AnswerA

Generators yield values on demand, saving memory.

Why this answer

Generators provide a lazy evaluation mechanism to yield items one at a time.

13
MCQeasy

Which magic method is used to define how an object is displayed for developers (for debugging)?

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

__repr__ is for developer-focused, unambiguous representation.

Why this answer

__repr__ is the magic method used to provide an unambiguous string representation of an object.

14
MCQeasy

Which keyword is used to raise an exception in Python?

A.trigger
B.throw
C.raise
D.catch
AnswerC

raise is the correct Python keyword.

Why this answer

The raise keyword is used to trigger an exception.

15
MCQmedium

You are designing a class hierarchy where a subclass needs to ensure it calls the constructor of its parent in a multiple inheritance scenario. Which mechanism is the standard Pythonic approach to handle this dynamically?

A.Using super().__init__()
B.Explicitly calling ParentClass.__init__(self)
C.Manually tracking parent states in a registry
D.Using the __init__subclass__ hook
AnswerA

super() correctly traverses the MRO, ensuring all classes are initialized only once.

Why this answer

super() is the standard way to delegate to the next class in the Method Resolution Order (MRO).

16
Multi-Selectmedium

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

Select 2 answers
A.Defining a function containing the 'yield' keyword
B.Calling the gen() function on a class
C.Using the @generator decorator
D.Using a list comprehension with brackets
E.Using a generator expression with parentheses
AnswersA, E

This defines a generator function.

Why this answer

Generators can be created via generator expressions (using parentheses) or generator functions (using the yield keyword).

17
MCQmedium

You need to ensure that a method can be called on the class directly, without requiring an instance. Which decorator should be used?

A.@classmethod
B.@property
C.@abstractmethod
D.@staticmethod
AnswerA

@classmethod receives the class reference.

Why this answer

The @classmethod decorator receives the class as the first argument, allowing factory-style methods.

18
Multi-Selecthard

Which TWO of the following are true about the 'descriptor protocol' in Python?

Select 2 answers
A.Descriptors must be defined inside a metaclass
B.A descriptor is a class that implements __get__, __set__, or __delete__
C.Descriptors are only used for methods
D.Descriptors can be used to customize attribute access
E.Descriptors automatically make an object serializable
AnswersB, D

This is the core definition of the descriptor protocol.

Why this answer

Descriptors define __get__, __set__, or __delete__, and they allow objects to customize attribute access.

19
MCQmedium

You need to compare two objects for equality based on a custom attribute. Which method should you override?

A.__hash__
B.__identical__
C.__eq__
D.__cmp__
AnswerC

__eq__ implements the equality operator.

Why this answer

The __eq__ magic method defines the behavior of the equality operator (==).

20
MCQmedium

When writing a context manager using the @contextlib.contextmanager decorator, what should the function do to pass a value to the 'as' clause?

A.Assign to a global variable
B.Use the return statement
C.Yield the value
D.Raise an exception
AnswerC

Yielding passes control to the block inside the with statement and provides the value.

Why this answer

The yield statement in a decorated generator function passes the value to the with statement's as target.

21
MCQhard

You are using 'slots' to save memory. What is a significant side effect of defining __slots__ in a class?

A.Methods cannot be defined
B.The class cannot be inherited from
C.Dynamic attribute addition is disabled
D.The class becomes immutable
AnswerC

Instances cannot have attributes assigned outside the defined slots.

Why this answer

Classes with __slots__ do not allow the creation of new attributes dynamically unless '__dict__' is explicitly included in __slots__.

22
MCQmedium

You want to store an object in a set. What must the object implement?

A.__iter__
B.__hash__ and __eq__
C.__set__
D.__init__ only
AnswerB

These are the requirements for an object to be hashable.

Why this answer

To be hashable (and thus stored in a set), an object must implement __hash__ and have equality defined via __eq__.

23
MCQhard

You are profiling your code and identify that a specific method is called millions of times. You decide to use a descriptor to optimize attribute access. What must the descriptor implement to intercept attribute assignment?

A.The __call__ method
B.The __init__ method
C.Only the __get__ method
D.The __set__ method
AnswerD

__set__ allows the descriptor to intercept and handle assignment.

Why this answer

A data descriptor is defined as an object that implements both __get__ and __set__ (or __delete__).

24
MCQeasy

When optimizing Python code, which tool should you use to identify hot spots in the execution path?

A.pydoc
B.pdb
C.unittest
D.cProfile
AnswerD

cProfile provides deterministic profiling of Python programs.

Why this answer

cProfile is the standard built-in profiler in Python for identifying performance bottlenecks.

25
Multi-Selecteasy

Which TWO of the following are Python object-oriented concepts?

Select 2 answers
A.Global functions
B.Pointers
C.Polymorphism
D.Inheritance
E.Header files
AnswersC, D

Polymorphism allows objects to be treated as instances of their parent class.

Why this answer

Inheritance and Polymorphism are fundamental OOP pillars in Python.

26
Multi-Selecthard

Which THREE of the following are true about Python metaclasses?

Select 3 answers
A.Metaclasses are instances of 'type'
B.A metaclass is defined by inheriting from 'type'
C.They are used to create instances directly
D.They are required for all classes in Python 3
E.They allow modification of the class object during creation
AnswersA, B, E

In Python, metaclasses are subclasses of 'type'.

Why this answer

Metaclasses are types, they allow modifying class creation, and they are defined by inheriting from 'type'.

27
MCQhard

You have a performance-critical application using heavy objects. You want to reduce memory footprint by preventing the creation of __dict__ for every instance. How should you proceed?

A.Use a decorator to delete __dict__ after creation
B.Inherit from the object class exclusively
C.Define a __slots__ sequence attribute
D.Set __dict__ = None in the class body
AnswerC

__slots__ explicitly defines the allowed attributes, saving memory by removing the instance-specific dictionary.

Why this answer

Defining __slots__ in a class prevents the creation of __dict__ and __weakref__ for instances, significantly reducing memory usage.

28
MCQmedium

You need to dynamically add methods to a class at runtime. Which mechanism allows you to modify the class object before it is fully constructed?

A.Inheritance
B.Metaclasses
C.Monkey patching
D.Class decorators
AnswerB

Metaclasses control the creation of the class itself.

Why this answer

Metaclasses, specifically the __new__ method, allow for the modification of class creation.

29
MCQeasy

Which built-in function allows you to retrieve an attribute from an object by its string name?

A.fetch()
B.getattribute()
C.access()
D.getattr()
AnswerD

getattr(obj, 'name') returns the value of the attribute.

Why this answer

getattr() is the built-in function to access object attributes dynamically.

30
Multi-Selectmedium

Which THREE of the following can be used to improve the performance of a Python application?

Select 3 answers
A.Adding more decorators to classes
B.Using cProfile to find bottlenecks
C.Disabling the garbage collector
D.Utilizing C-implemented built-ins instead of loops
E.Replacing slow algorithms with more efficient ones
AnswersB, D, E

Profiling is essential for performance tuning.

Why this answer

Profiling, algorithm optimization, and using built-in C-implemented functions are key strategies.

31
Multi-Selecthard

Which TWO of the following statements about the Python Method Resolution Order (MRO) are true?

Select 2 answers
A.You can inspect MRO using the __mro__ attribute
B.The mro() method returns the linearization of classes
C.MRO applies only to single inheritance
D.MRO is determined by the depth-first search
E.MRO changes randomly at runtime
AnswersA, B

__mro__ stores the calculated resolution order.

Why this answer

MRO uses the C3 linearization algorithm and it can be inspected via the __mro__ attribute or the mro() method.

32
Multi-Selectmedium

Which THREE of the following are benefits of using __slots__?

Select 3 answers
A.Faster attribute access
B.Reduced memory footprint
C.Automatic support for multiple inheritance
D.Automatic serialization
E.Prevention of __dict__ creation
AnswersA, B, E

Attribute access can be faster due to the structure of slots.

Why this answer

__slots__ reduces memory usage, prevents the creation of __dict__, and can potentially speed up attribute access.

Ready to test yourself?

Try a timed practice session using only Advanced Oop And Performance questions.