Python Interview Questions with Answers Page II


From freshersonline.com

Jump to: navigation, search

Interview Question Home

1. What is a class?

A class is the particular object type created by executing a class statement. Class objects are

used as templates to create instance objects, which embody both the data (attributes) and code

(methods) specific to a datatype.


A class can be based on one or more other classes, called its base class(es). It then inherits

the attributes and methods of its base classes. This allows an object model to be successively

refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods

for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various

specific mailbox formats.


2. What is a class?

A class is the particular object type created by executing a class statement. Class objects are used

as templates to create instance objects, which embody both the data (attributes) and code (methods)

specific to a datatype.


A class can be based on one or more other classes, called its base class(es). It then inherits the

attributes and methods of its base classes. This allows an object model to be successively refined by

inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox,

and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats.


3. What is self?


Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c)

should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called

method will think it is called as meth(x, a, b, c).


4. What is a method?

A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined

as functions inside the class definition:


class C:

def meth (self, arg):

return arg*2 + self.attribute


5. How can I organize my code to make it easier to change the base class?


You could define an alias for the base class, assign the real base class to it before your class definition,

and use the alias throughout your class. Then all you have to change is the value assigned to the alias.

Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability

of resources) which base class to use. Example:


BaseAlias = <real base class>

class Derived(BaseAlias):

def meth(self):

BaseAlias.meth(self)


6. How can I overload constructors (or methods) in Python?


This answer actually applies to all methods, but the question usually comes up first in the context of constructors.


In C++ you'd write


class C {

C() { cout << "No arguments\n"; }

C(int i) { cout << "Argument is " << i << "\n"; }

}


in Python you have to write a single constructor that catches all cases using default arguments. For example:


class C:

def __init__(self, i=None):

if i is None:

print "No arguments"

else:

print "Argument is", i


This is not entirely equivalent, but close enough in practice.


You could also try a variable-length argument list, e.g.


def __init__(self, *args):

....


The same approach works for all method definitions.


7. How do I share global variables across modules?


The canonical way to share information across modules within a single program is to create a special

module (often called config or cfg). Just import the config module in all modules of your application;

the module then becomes available as a global name. Because there is only one instance of each module,

any changes made to the module object get reflected everywhere. For example:


config.py:

x = 0 # Default value of the 'x' configuration setting

mod.py:

import config

config.x = 1


main.py:

import config

import mod

print config.x


Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.


8. How can I pass optional or keyword parameters from one function to another?


Collect the arguments using the * and ** specifiers 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):

... kwargs['width']='14.3c'


...

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):

...

kwargs['width']='14.3c'

...

apply(g, (x,)+tup, kwargs)


9. Is there an equivalent of C's "?:" ternary operator?


No.


10. How do I copy a file?


The shutil module contains a copyfile() function.


11. How do I delete a file? (And other file questions...)


Use os.remove(filename) or os.unlink(filename);


12. How do I read (or write) binary data?


or complex data formats, it's best to use the struct module. It allows you to take a string

containing binary data (usually numbers) and convert it to Python objects; and vice versa.


For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:


import struct


f = open(filename, "rb") # Open in binary mode for portability

s = f.read(8)

x, y, z = struct.unpack(">hhl", s)


The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes),

and 'l' reads one "long integer" (4 bytes) from the string.

Personal tools