Python Interview Questions and Answers
Ques 6. How can I pass optional or keyword parameters from one function to another?
Ans. Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:
def f(x, *tup, **kwargs):
g(x, *tup, **kwargs)
In the unlikely case that you care about Python versions older than 2.0, use 'apply': def f(x, *tup, **kwargs):
apply(g, (x,)+tup, kwargs)
Ques 7. How do you make a higher order function in Python?Ans. You have two choices: you can use nested scopes or you can use callable objects. For example,
suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:
return a*x + b
Or using a callable object:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b
In both cases:
taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
Object can encapsulate state for several methods:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set
Here inc(), dec() and reset() act like functions which share the same counting variable.
Ques 8. How do I copy an object in Python?Ans. In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a copy() method: newdict = olddict.copy()
Sequences can be copied by slicing: new_l = l[:]
Ques 9. How can I find the methods or attributes of an object?Ans. For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.
Ques 10. How do I convert a string to a number?Ans. For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0.
By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError. int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number.
Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory.
eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8).
Most helpful rated by users: