Hewlett Packard Python Recent Asked Interview Questions Answers

What Are The Rules For Local And Global Variables In Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.
Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

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

How Do I Copy An Object In Python?

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[:]

What Are The Built-In Types Available In Python?

Here is the list of most commonly used built-in types that Python supports:

Immutable built-in types of Python

Numbers
Strings
Tuples

Mutable built-in types of Python

List
Dictionaries
Sets

How To Find Bugs Or Perform Static Analysis In A Python Application?

You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.

Write a program to check whether the object is of a class or its subclass ?

There is a method which is built-in to show the instances of an object that consists of many classes by providing a tuple in a table instead of individual classes. The method is isinstance(obj,cls)

isinstance(obj, (class1, class2, ...)) is used to check the object’s presence in one of the classes. The built in types can also have many formats of the same function like isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).

It is not preferred to use the class instead user-defined classes are made that allow easy object-oriented style to define the behavior of the object’s class. These perform different thing based on the class. The function differs from one class to another class.

To find out the object of the particular class the following program is used:
def search(obj):
if isinstance(obj, box):

# This is the code that is given for the box and write the program in the object
elif isinstance(obj, Document):

# This is the code that searches the document and writes the values in it
elif
obj.search()

#This is the function used to search the object’s class.
Explain delegation in Python
Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x. The example shows a class that captures the behavior of the file and converts data from lower to uppercase.

class upcase:

def __init__(self, out):
self._out = out
def write(self, s):
self._outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self._out, name)

The write() method is used in the upcase class converts the string to the uppercase before calling another method. The delegation is being given using the self.__outfile object.

What is the function of “self”?

“Self” is a variable that represents the instance of the object to itself. In most of the object oriented programming language, this is passed to the methods as a hidden parameters that is defined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects. This is the first argument used in the class instance and the “self” method is defined explicitly to all the methods that are used and present. The variables are referred as “self.xxx”.

How is “self” explicitly defined in a method?

“Self” is a reference variable and an instance attribute that is used instead of the local variable inside the class. The function or the variable of the self like self.x or self.meth() can be used in case the class is not known. There are no variables declared as local. It doesn’t have any syntax and it allow the reference to be passed explicity or call the method for the class that is in use. The use of writebaseclass.methodname(self, <argument list>) shows that the method of _init_() can be extended to the base class methods. This also solves the problem that is syntactic by using the assignment and the local variables. This tells a way to the interpreter the values that are to be used for the instance variables and local variables. The use of explicit self.var solves the problem mentioned above.

What is the process of compilation and linking in python?

The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files.

The steps required are as follows:

- Create a file with any name and in any languages supported by the compiler of your system. For example comp.c
- Place this file in the Modules/ directory of the distribution which is getting used.
- Add a line in the file Setup.local present in the Modules/ directory.
- Run the file using spam comp.o
- After successful run of this rebuild the interpreter by using the make command on the top-level directory.
- If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

What is the procedure to extract values from the object used in python?

To extract the value it requires the object type to be defined and the values are fetched according to the object type.

The values are extracted as:

- If the object is a tuple then PyTuple_Size() method is used that returns the length of the values and the method PyTuple_GetItem() returns the data item stored at a specific index.
- If the object is a list then PyListSize() and PyList_GetItem() perform the same function as they are for tuple.
- Strings use PyString_Size() to return the length of the value and PyString_AsString() returns the pointer to its value.
- To check the type of the object and the extracted values, methods like PyString_Check(), PyTuple_Check(), PyList_Check(), etc are used.

What is the output of print tuple[2:] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print elements starting from 3rd element. Output would be (2.23, ‘john’, 70.200000000000003).

What is the output of print tinytuple * 2 if tinytuple = (123, ‘john’)?

It will print tuple two times. Output would be (123, ‘john’, 123, ‘john’).

What are the steps required to make a script executable on Unix?

The steps required to make a script executable are:

- First create a script file and write the code that has to be executed in it.

- Make the file mode as executable by making the first line starts with #! this is the line that python interpreter reads.

- Set the permission for the file by using chmod +x file. The file uses the line which is the most important line to be used:
#!/usr/local/bin/python

- This explains the pathname that is given to the python interpreter and it is independent of the environment programs.

- Absolute pathname should be included so that the interpreter can interpret and execute the code accordingly. The sample code that is written:

#! /bin/sh
# Write your code here
exec python $0 ${1+"$@"}
# Write the function that need to be included.

How does global value mutation used for thread-safety?

The global interpreter lock allows the running of the thread one at a time. This is used to distribute the functionality among all the virtual machines that are used. Python allows the switching between the threads to be performed by using the byte code instructions to provide platform-independence. The sys.setcheckinterval() method is used to allow the switching to occur during the implementation of the program and the instruction. This provides the understanding in the field of accounting to use the byte code implementation that makes it portable to use. The atomicity can be provided such that the shared variables can be given as built-in data types.

Write a program to read and write the binary data using python?

The module which is used to write and read the binary data is known as struct. This module allows many functionalities to be used that consist of the string class. This class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is:

import struct
f = open(file-name, "rb")
# This Open() method allows the file to get opened in binary mode to make it portable for # use.
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
The ‘>” is used to show the format string that allows the string to be converted in big-endian data form. For homogenous list of data the array module can be used that will allow the data to be kept in more organized fashion.

What is the output of print tuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print complete tuple. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003).

What is the output of print tuple[0] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print first element of the tuple. Output would be abcd.

Name some of the features of Python.


Following are some of the salient features of python

It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

How will you convert an integer to octal string in python?

oct(x) − Converts an integer to an octal string.

What is the purpose of ** operator?

** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

What is __init__.py used for?

It declares that the given directory is a  package. #Python Docs (From Endophage‘s comment).


Post a Comment

Previous Post Next Post