PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 17
You are developing a Python class called Employee to manage employee data in a large organization. Each Employee object should be able to store a flexible number of details such as name, age, department, and any additional information provided. You decide to use *args for positional arguments and **kwargs for keyword arguments to achieve this flexibility. Here is the class definition:
- class Employee:
- def __init__(self, name, age, *args, **kwargs):
- self.name = name
- self.age = age
- self.details = args
- self.extra_info = kwargs
- def get_summary(self):
- return (
- f"Employee: {self.name}, Age: {self.age}, Details: "
- f"{self.details}, Extra Info: {self.extra_info}"
- )
You create an instance of the Employee class as follows:
- employee = Employee(
- "John Doe",
- 30,
- "Engineering",
- "Full-Time",
- salary=70000,
- location="New York",
- )
- print(employee.get_summary())
Which of the following statements best describes the behavior of the code above?
-
A
The keyword arguments
salaryandlocationwill be ignored since they are not explicitly handled in theEmployeeclass. -
B
The
get_summarymethod will print the details and extra information correctly, showing both positional and keyword arguments. -
C
The
argsandkwargsshould be reversed in the__init__method to correctly capture all arguments. -
D
The code will raise a
TypeErrorbecause theEmployeeclass does not expect thesalaryandlocationarguments.
Reveal correct answer
Correct answer: B
A.
The keyword arguments salary and location are not ignored; they are stored in the extra_info attribute as a dictionary, which will also be displayed when get_summary is called.
B.
The *args and **kwargs syntax in Python allows the Employee class to accept additional positional and keyword arguments. In this scenario, the get_summary method will correctly print the name, age, and all extra details passed to the Employee instance. The *args captures positional arguments ("Engineering", "Full-Time") as a tuple, and **kwargs captures keyword arguments (salary=70000, location="New York") as a dictionary. This flexible argument handling is functioning as intended.
C.
Reversing args and kwargs in the method signature would result in a syntax error. *args must come before **kwargs in the parameter list, as this is the correct order in Python’s syntax.
D.
The code does not raise a TypeError because the *args and **kwargs allow for an arbitrary number of additional arguments without needing to explicitly declare them in the method signature.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
