Python Interview Questions with Answers Page III
From freshersonline.com
1. __import__('x.y.z') returns < module 'x'>; how do I get z?
Try:
__import__('x.y.z').y.z
For more realistic situations, you may have to do something like
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)
2. How do I call a method defined in a base class from a derived class that overrides it?
If you're using new-style classes, use the built-in super() function:
class Derived(Base):
def meth (self):
super(Derived, self).meth()
If you're using classic classes: For a class definition such as class Derived(Base): ... you can call
method meth() defined in Base (or one of Base's base classes) as Base.meth(self, arguments...). Here,
Base.meth is an unbound method, so you need to provide the self argument.
3. How do I find the current module name?
A module can find out its own module name by looking at the predefined global variable How do I find
the current module name?. If this has the value '__main__', the program is running as a script.
Many modules that are usually used by importing them also provide a command-line interface or a self-test,
and only execute this code after checking How do I find the current module name?:
def main():
print 'Running test...'
...
if How do I find the current module name? == '__main__':
main()
4. How do I apply a method to a sequence of objects?
Use a list comprehension:
result = [obj.method() for obj in List]
More generically, you can try the following function:
def method_map(objects, method, arguments):
"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)
5. Is a *.pyd file the same as a DLL?
Yes, .
6. Why don't my signal handlers work?
The most common problem is that the signal handler is declared with the wrong argument list. It is called as
handler(signum, frame)
so it should be declared with two arguments:
def handler(signum, frame):
...
