Wednesday, September 15, 2010

Python interview questions (2)

Python interview question (1)

8. What is self in python?
The first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically.


For example:
>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5) 
 
9. What is class and method?
 
 Class objects are used as  templates to create
 instance objects, which embody both   data 
  and methods. Methods are defined as functions inside
  the class definition.



class BaseClass:
    # This data will exist in all
    # BaseClasses (even uninstantiated ones)
    Name = "BaseClass"
    # __init__ is a class constructor
    # __****__ is usually a special class method.
    def __init__(self, arg1, arg2):
        # These values are created
        # when the class is instantiated.
        self.value1 = arg1
        self.value2 = arg2

    # Self is used as an argument to
    # pretty much all class functions.
    # However, you do NOT need to pass
    # the argument self if you call this method
    # from a Class, because the class provides
    # the value of itself.
    def display(self):
        print self.Name
        print self.value1
        print self.value2

        
 10. How do I make a Python script executable on Unix? 

You need to do two things: the script file's mode must 
be executable and the first line must begin with #! 
followed by the path of the Python interpreter. 

The first is done by executing chmod +x scriptfile or 
perhaps chmod 755 scriptfile. 

The second can be done in a number of ways. The most 
straightforward way is to write 

#!/usr/local/bin/python 

as the very first line of your file, using the pathname 
for where the Python interpreter is installed on your 
platform. 

If you would like the script to be independent of where 
the Python interpreter lives, you can use the "env" 
program. Almost all Unix variants support the following, 
assuming the python interpreter is in a directory on the 
user's $PATH: 

#! /usr/bin/env python 

1 comment: