Python is very popular programming language with many job offers. I collected some questions (with answers) from many students interviews. Test yourself: are you ready to work with python?
1. Base and derived classes:
Look at the following code:
Is it possible to make obj call the base class show? In other words I want to cast obj to type A
Answer:
The __class__ attribute points to the class object, just change it to point to A and call the function, don’t forget to change it back!!!
2. Function Object
What do you need to add to make this code run, i.e. use object as a function:
Answer:
To make an object callable, implement __call__ method:
3. New and Init
What will be printed:
Answer:
In __new__ you can decide which object to return – use it as a factory , the __init__ function is called on the created object class
4. Python Collections Comprehension
What will be printed
Answer:
All the above statements build and return a collection based on another.
5. Globals and locals
What is the output of the following code:
Answer:
num is not a global variable so each function gets its own copy, what do you need to add to make it work as a global variable?
Answer:
6. Swap numbers
Swap a and b in one line
Answer:
7. Default method
Look at the following code:
fn1,fn2,fn3 are not declared, add the code to make any undeclared function to be replaced with mydefault, i.e. the above code output is:
Answer:
The special method __getattr__ is invoked if an undeclared method is called. It returns the default function that replaces it. In this case the function is called without parameters but you can add *args to make it replace any function
8. Packages and modules
Given a package ‘demopack’ with 3 modules: mod1.py, mod2.py, mod3.py. What do you need to write to make the package exports only mod1,mod3 when using:
Answer:
Add __init__.py to the package and add the following line:
9. Closure
Write a function ‘mulby’ that gets an integer parameter n and returns a function that multiplies its input by n
Answer:
10. Performance
Explain why this code is slow:
Answer:
Python strings are immutable, on each iteration the a new string is created. Calling the function with num=500 it will create 500 different strings with len ranging from 5 to 505 and cost at about 25000 characters – 50kb of memory for 505 characters string as a result