All sample questions / Python
Python Classes, Objects and Special Methods, what does print(c.host, c.port) print after class Config?
Block 3, Classes, Objects and Special Methods, question 15 of the Python sample
class Config:
def __init__(self, **kwargs):
self._data = kwargs
def __getattr__(self, name):
try:
return self._data[name]
except KeyError:
raise AttributeError(name)
c = Config(host='localhost', port=8080)
print(c.host, c.port)
What does this print?
Show the answer and why each option is right or wrong
Answer, D. localhost 8080
- A. None None
- Assumes the fallback returns nothing usable for keys that were never set as real attributes. Both host and port were passed as keyword arguments and stored in _data, so the fallback finds and returns each of them.
- B. AttributeError
- Assumes accessing keys that only live inside the internal dictionary always fails with an error. __getattr__ specifically catches the missing attribute case and redirects it to a dictionary lookup, returning the stored value instead of failing, since both keys exist.
- C. localhost 80
- Truncates the port number as if only part of it were stored or printed. The full integer 8080 is stored in the dictionary and returned exactly as it was passed in.
- D. localhost 8080
- Correct. host and port are not real attributes, so each access triggers __getattr__, which looks them up in the stored dictionary.
Storing arbitrary keyword arguments in a dictionary and then defining __getattr__ to look names up in that dictionary is a common way to expose dynamic attributes without declaring them individually. Since __getattr__ only runs for names missing from the instance, and host and port were never set directly, both accesses are redirected into the stored dictionary.
The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 Python questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free Python sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.