Вы находитесь на странице: 1из 20

What are the ways to write a function using

call by reference?
Arguments in python are passed as an assignment. This assignment creates an object that has no relationship
between an argument name in source and target. The procedure to write the function using call by reference
includes:
The tuple result can be returned to the object which called it. The example below shows it:
def function(a, b):
a = 'value'
b=b+1
# a and b are local variables that are used to assign the new objects
return a, b
# This is the function that is used to return the value stored in b
- The use of global variables allows the function to be called as reference but this is not the safe method to call
any function.
- The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the
function by reference.
def function(a):
a[0] = 'string'
a[1] = a[1] + 1
# The a array give reference to the mutable list and it changes the changes that are shared
args = ['string', 10]
func1(args)
print args[0], args[1]
#This prints the value stored in the array of a

What are the commands that are used to copy an


object in Python?
The command that is used to copy an object in python includes:
- copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of
the parameter that is passed.
- copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of
the parameter that is passed to the function.
The dictionary consists of all the objects and the copy() method which is used as:
newdict = olddict.copy()

The assignment statement doesnt copy any object but it creates a binding between the target and the object
that is used for the mutable items. Copy is required to keep a copy of it using the modules that is provided to
give generic and shallow operations.

What is the difference between deep and shallow


copy?
- Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the
new instance. Whereas, deep copy is used to store the values that are already copied.
- Shallow copy is used to copy the reference pointers just like it copies the values. These references point to
the original objects and the changes made in any member of the class will also affect the original copy of it.
Whereas, deep copy doesnt copy the reference pointers to the objects. Deep copy makes the reference to an
object and the new object that is pointed by some other object gets stored. The changes made in the original
copy wont affect any other copy that uses the object.
- Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Whereas, deep copy makes it slower due to making certain copies for each object that is been called.

Write a program to find out the name of an


object in python.
The object doesnt have any name and there is no way the can be found out for objects. The assignment is
used to bind a name to the value that includes the name of the object that has to be bound by a value. If the
value is callable then the statements are made true and then the program followed can be used to find the
reference name of an object.
class try:
pass
B=A
a = B()
b=a
print b
<__main__.try instance at 0x16D07CC>
print b
The class consists of name and the names are invoked by using the the variable B that creates an instance for
the class try. The method is to find out from all the namespaces that the object exists and then print the name
of the object.

How can the ternary operators be used in

python?
The ternary operator is the operator that is used to show the conditional statements. This consists of the true or
false values with a statement that has to be evaluated for it. The operator will be given as:
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y
This is the lowest priority operator that is used in making a decision that is based on the values of true or false.
The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x
and if it is incorrect then big=y will be sent as a result.

How the string does get converted to a number?


- To convert the string into a number the built-in functions are used like int() constructor. It is a data type that
is used like int (1) ==1.
- float() is also used to show the number in the format as float(1)=1.
- The number by default are interpreted as decimal and if it is represented by int(0x1) then it gives an
error as ValueError. In this the int(string,base) function takes the parameter to convert string to number in this
the process will be like int(0x1,16)==16. If the base parameter is defined as 0 then it is indicated by an
octal and 0x indicates it as hexadecimal number.
- There is function eval() that can be used to convert string into number but it is a bit slower and present many
security risks like __import__('os').system("rm -rf$HOME") - use of this will delete the home directory of the
system.

What is the function of negative index?


The sequences in python are indexed and it consists of the positive as well as negative numbers. The numbers
that are positive uses 0 that is uses as first index and 1 as the second index and the process goes on
like that. The index for the negative number starts from -1 that represents the last index in the sequence
and -2 as the penultimate index and the sequence carries forward like the positive number. The negative
index is used to remove any new-line spaces from the string and allow the string to except the last character
that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct
order.

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 given as isinstance(obj,cls) and in
more details given as:
isinstance(obj, (class1, class2, ...)) that is used to check about the objects 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 objects class. These perform different thing that is 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 objects class.

Why does delegation performed in Python?


Delegation is a technique that is used in object oriented programming. This is used to show the object and the
behavior of the methods that are used. The class can be created to provide an implementation of the method
that allows the method to be referenced. The delegate is having the parameter and the return value in an object.
It also allows the methods to be passed as parameters and allow the defining of the callback methods that can
be grouped together in multiple methods. These methods can be called from a single event. 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 that 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 represent the instance of the object to itself. In most of the object oriented
programming language, this is passed as to the methods as a hidden parameters that is defined by an object.
But, in python it is declare it and pass it 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 that is 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 doesnt 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 use of join() for a string rather


than list or tuple method?
The functions and the methods that are used for the functionality uses the string module. This string module is
represented as by using the join function in it:
", ".join(['1', '2', '4', '8', '16']) that results in "1, 2, 4, 8, 16"
The string variable that is used provide a fixed string literal to allow the names that are used to be bounded to
the strings. join() is a string method that is used to provide a separator string to use the function over the
sequence of the string and insert the function to an adjacent elements. The method uses any number of
arguments that follow some rules that has to be put up for the sequence objects that the class defines for itself.
The join is used for the string module that is used to join the string characters together as it is given in the
program. The example is given as:

string.join(['1', '2', '4', '8', '16'], ", ")

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 and will rebuild the interpreter.
The steps that is required in this as:
- Create a file with any name and in any lanugage that is 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 that is 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 according to the object type only the values
will be fetched.
The values will be extracted as:
- If the object is a tuple then PyTuple_Size() method is used that returns the length of the values and another
method PyTuple_GetItem() returns the data item that is stored at a specific index.
- If the object is a list then PyListSize() is having the same function that is defined for the tuple and
PyList_GetItem() that also return the data items at a specified index.
- Strings uses PyString_Size() to return the length of the value and PyString_AsString() that return the pointer
to its value.
- To check the type of the object and the extracted values use of methods like PyString_Check(),
PyTuple_Check(), PyList_Check(), etc are used.

What are the steps required to make a script


executable on Unix?
The steps that are required to make a script executable are to:

- 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 that 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 threadsafety?


The global interpreter lock is used to allow the running of the thread one at a time. This is internal to the
program only and used to distribute the functionality along all the virtual machines that are used. Python
allows the switching between the threads to be performed by using the byte code instructions that are used to
provide platform-independence. The sys.setcheckinterval() method is used that 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 that is used to write and read the binary data is known as struct. This module allows the
functionality and with it many functionalities to be used that consists 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 more organized
fashion.

What is the process to run sub-process with


pipes that connect both input and output?
The popen2() module is used to run the sub-process but due to some difficulty in processing like creation of
deadlock that keep a process blocked that wait for the output from the child and child is waiting for the input.
The dead lock occurs due to the fact that parent and child doesnt have the synchronization and both are
waiting to get the processor to provide the resources to one another. Use of popen3() method allow the reading
of stdout and stderr to take place where the internal buffer increases and there is no read() takes place to share
the resources. popen2() take care of the deadlock by providing the methods like wait() and waitpid() that
finishes a process first and when a request comes it hands over the responsibility to the process that is waiting
for the resources.
The program is used to show the process and run it.
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()

What are the different ways to generate random


numbers?
Random module is the standard module that is used to generate the random number.
The method is defined as:
import random
random.random()
The statement random.random() method return the floating point number that is in the range of [0, 1). The
function generates the random float numbers. The methods that are used with the random class are the bound
methods of the hidden instances. The instances of the Random can be done to show the multi-threading
programs that creates different instance of individual threads. The other random generators that are used in this
are:
- randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by
selecting it randomly from the range that is specified. It doesnt build a range object.

- uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating
point number
- normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a
sigma that is used for standard deviation.
- The Random class that is used and instantiated creates an independent multiple random number generators.

Write a program to show the singleton pattern


used in python.
Singleton patter is used to provide a mechanism that limits the number of instances that can be used by one
class. It also allows the same object to be shared between many different parts of the code. This allows the
global variables to be used as the actual data that is used is hidden by the singleton class interface. The
singleton class interface can have only one public member and one class method Handle. Private constructors
are not used to create an object that is used outside the class. The process waits for the static member function
to create new instances and return the singleton object.
The code that is used to call the singleton object is:
Singleton& Singleton::Handle()
{
if( !psingle )
{
psingle = new Singleton;
}
return *psingle;
}

Python in the Weeds


While its true that the best developers dont waste time committing to memory
that which can easily be found in a language specification or API document,
there are certain key features and capabilities of any programming language that
any expert can, and should, be expected to be well-versed in. Here are some
Python-specific examples:
Q: Why use function decorators? Give an example.
A decorator is essentially a callable Python object that is used to modify or extend a
function or class definition. One of the beauties of decorators is that a single decorator
definition can be applied to multiple functions (or classes). Much can thereby be

accomplished with decorators that would otherwise require lots of boilerplate (or even
worse redundant!) code. Flask, for example, uses decorators as the mechanism for
adding new endpoints to a web application. Examples of some of the more common
uses of decorators include adding synchronization, type enforcement, logging, or
pre/post conditions to a class or function.
Q: What are lambda expressions, list comprehensions and generator expressions?
What are the advantages and appropriate uses of each?
Lambda expressions are a shorthand technique for creating single line, anonymous
functions. Their simple, inline nature often though not always leads to more
readable and concise code than the alternative of formal function declarations. On the
other hand, their terse inline nature, by definition, very much limits what they are
capable of doing and their applicability. Being anonymous and inline, the only way to
use the same lambda function in multiple locations in your code is to specify it
redundantly.
List comprehensions provide a concise syntax for creating lists. List comprehensions
are commonly used to make lists where each element is the result of some
operation(s) applied to each member of another sequence or iterable. They can also be
used to create a subsequence of those elements whose members satisfy a certain
condition. In Python, list comprehensions provide an alternative to using the builtin map()and filter() functions.
As the applied usage of lambda expressions and list comprehensions can overlap,
opinions vary widely as to when and where to use one vs. the other. One point to bear
in mind, though, is that a list comprehension executes somewhat faster than a
comparable solution using map and lambda (some quick tests yielded a performance
difference of roughly 10%). This is because calling a lambda function creates a new
stack frame while the expression in the list comprehension is evaluated without doing
so.
Generator expressions are syntactically and functionally similar to list
comprehensions but there are some fairly significant differences between the ways the
two operate and, accordingly, when each should be used. In a nutshell, iterating over a
generator expression or list comprehension will essentially do the same thing, but the
list comprehension will create the entire list in memory first while the generator
expression will create the items on the fly as needed. Generator expressions can
therefore be used for very large (and even infinite) sequences and their lazy (i.e., on
demand) generation of values results in improved performance and lower memory
usage. It is worth noting, though, that the standard Python list methods can be used on
the result of a list comprehension, but not directly on that of a generator expression.

Q: Consider the two approaches below for initializing an array and the arrays that
will result. How will the resulting arrays differ and why should you use one
initialization approach vs. the other?
>>> # INITIALIZING AN ARRAY -- METHOD 1
...
>>> x = [[1,2,3,4]] * 3
>>> x
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
>>>
>>>
>>> # INITIALIZING AN ARRAY -- METHOD 2
...
>>> y = [[1,2,3,4] for _ in range(3)]
>>> y
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
>>>
>>> # WHICH METHOD SHOULD YOU USE AND WHY?

While both methods appear at first blush to produce the same result, there is an
extremely significant difference between the two. Method 2 produces, as you would
expect, an array of 3 elements, each of which is itself an independent 4-element array.
In method 1, however, the members of the array all point to the same object. This can
lead to what is most likely unanticipated and undesired behavior as shown below.
>>> # MODIFYING THE x ARRAY FROM THE PRIOR CODE SNIPPET:
>>> x[0][3] = 99
>>> x
[[1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99]]
>>> # UH-OH, DONT THINK YOU WANTED THAT TO HAPPEN!
...
>>>

>>> # MODIFYING THE y ARRAY FROM THE PRIOR CODE SNIPPET:


>>> y[0][3] = 99
>>> y
[[1, 2, 3, 99], [1, 2, 3, 4], [1, 2, 3, 4]]
>>> # THATS MORE LIKE WHAT YOU EXPECTED!
...

Q: What will be printed out by the second append() statement below?


>>> def append(list=[]):
...

# append the length of a list to the list

...

list.append(len(list))

...

return list

...
>>> append(['a','b'])
['a', 'b', 2]
>>>
>>> append()

# calling with no arg uses default list value of []

[0]
>>>
>>> append()

# but what happens when we AGAIN call append with no

arg?

When the default value for a function argument is an expression, the expression is
evaluated only once, not every time the function is called. Thus, once the list
argument has been initialized to an empty array, subsequent calls to append without
any argument specified will continue to use the same array to which list was
originally initialized. This will therefore yield the following, presumably unexpected,
behavior:
>>> append()

# first call with no arg uses default list value of []

[0]
>>> append()

# but then look what happens...

[0, 1]
>>> append()

# successive calls keep extending the same default

list!
[0, 1, 2]
>>> append()

# and so on, and so on, and so on...

[0, 1, 2, 3]

Q: How might one modify the implementation of the append method in the
previous question to avoid the undesirable behavior described there?
The following alternative implementation of the append method would be one of a
number of ways to avoid the undesirable behavior described in the answer to the
previous question:
>>> def append(list=None):
...

if list is None:
list = []
# append the length of a list to the list

...

list.append(len(list))

...

return list

...
>>> append()
[0]
>>> append()
[0]

Q: How can you swap the values of two variables with a single line of Python code?
Consider this simple example:
>>> x = 'X'
>>> y = 'Y'

In many other languages, swapping the values of x and y requires that you to do the
following:

>>> tmp = x
>>> x = y
>>> y = tmp
>>> x, y
('Y', 'X')

But in Python, makes it possible to do the swap with a single line of code (thanks to
implicit tuple packing and unpacking) as follows:
>>> x,y = y,x
>>> x,y
('Y', 'X')

Q: What will be printed out by the last statement below?


>>> flist = []
>>> for i in range(3):
...

flist.append(lambda: i)

...
>>> [f() for f in flist]

# what will this print out?

In any closure in Python, variables are bound by name. Thus, the above line of code
will print out the following:
[2, 2, 2]

Presumably not what the author of the above code intended!


A workaround is to either create a separate function or to pass the args by name; e.g.:
>>> flist = []
>>> for i in range(3):
...

flist.append(lambda i = i : i)

...
>>> [f() for f in flist]
[0, 1, 2]

Q: What are the key differences between Python 2 and 3?


Although Python 2 is formally considered legacy at this point, its use is still
widespread enough that is important for a developer to recognize the differences
between Python 2 and 3.
Here are some of the key differences that a developer should be aware of:

Text and Data instead of Unicode and 8-bit strings. Python 3.0 uses the concepts of text and
(binary) data instead of Unicode strings and 8-bit strings. The biggest ramification of this is
that any attempt to mix text and data in Python 3.0 raises a TypeError (to combine the two
safely, you must decode bytes or encode Unicode, but you need to know the proper
encoding, e.g. UTF-8)

This addresses a longstanding pitfall for nave Python programmers. In Python 2, mixing
Unicode and 8-bit data would work if the string happened to contain only 7-bit (ASCII)
bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. Moreover,
the exception would happen at the combination point, not at the point at which the nonASCII characters were put into the str object. This behavior was a common source of
confusion and consternation for neophyte Python programmers.
print function. The print statement has been replaced with a print() function

xrange buh-bye. xrange() no longer exists (range() now behaves like xrange() used
to behave, except it works with values of arbitrary size)

API changes:

zip(), map() and filter() all now return iterators instead of lists

dict.keys(), dict.items() and dict.values() now return views instead of lists

dict.iterkeys(), dict.iteritems() and dict.itervalues() are

no

longer

supported
Comparison operators. The ordering comparison operators (<, <=, >=, >) now raise
a TypeErrorexception when the operands dont have a meaningful natural ordering. Some
examples of the ramifications of this include:

Expressions like 1 < '', 0 > None or len <= len are no longer valid

None < None now raises a TypeError instead of returning False

Sorting a heterogeneous list no longer makes sense all the elements must be comparable to
each other

More details on the differences between Python 2 and 3 are available here.
Q: Is Python interpreted or compiled?
As noted in Why Are There So Many Pythons?, this is, frankly, a bit of a trick
question in that it is malformed. Python itself is nothing more than an interface
definition (as is true with any language specification) of which there are multiple

implementations. Accordingly, the question of whether Python is interpreted or


compiled does not apply to the Python language itself; rather, it applies to each
specific implementation of the Python specification.
Further complicating the answer to this question is the fact that, in the case of
CPython (the most common Python implementation), the answer really is sort of
both. Specifically, with CPython, code is first compiled and then interpreted. More
precisely, it is not precompiled to native machine code, but rather to bytecode. While
machine code is certainly faster, bytecode is more portable and secure. The bytecode
is then interpreted in the case of CPython (or both interpreted and compiled to
optimized machine code at runtime in the case of PyPy).
Q: What are some alternative implementations to CPython? When and why might
you use them?
One of the more prominent alternative implementations is Jython, a Python
implementation written in Java that utilizes the Java Virtual Machine (JVM). While
CPython produces bytecode to run on the CPython VM, Jython produces Java
bytecode to run on the JVM.
Another is IronPython, written in C# and targeting the .NET stack. IronPython runs
on Microsofts Common Language Runtime (CLR).
As also pointed out in Why Are There So Many Pythons?, it is entirely possible to
survive without ever touching a non-CPython implementation of Python, but there are
advantages to be had from switching, most of which are dependent on your
technology stack.
Another noteworthy alternative implementation is PyPy whose key features include:

Speed. Thanks to its Just-in-Time (JIT) compiler, Python programs often run faster on PyPy.

Memory usage. Large, memory-hungry Python programs might end up taking less space with
PyPy than they do in CPython.

Compatibility. PyPy is highly compatible with existing python code. It supports cffi and can
run popular Python libraries like Twisted and Django.

Sandboxing. PyPy provides the ability to run untrusted code in a fully secure way.

Stackless mode. PyPy comes by default with support for stackless mode, providing microthreads for massive concurrency.

Q: Whats your approach to unit testing in Python?


The most fundamental answer to this question centers around Pythons unittest testing
framework. Basically, if a candidate doesnt mention unittest when answering this
question, that should be a huge red flag.

unittest supports test automation, sharing of setup and shutdown code for tests,
aggregation of tests into collections, and independence of the tests from the reporting
framework. The unittest module provides classes that make it easy to support these
qualities for a set of tests.
Assuming that the candidate does mention unittest (if they dont, you may just want to
end the interview right then and there!), you should also ask them to describe the key
elements of the unittest framework; namely, test fixtures, test cases, test suites and test
runners.
A more recent addition to the unittest framework is mock. mock allows you to replace
parts of your system under test with mock objects and make assertions about how they
are to be used. mock is now part of the Python standard library, available as
unittest.mock in Python 3.3 onwards.
The value and power of mock are well explained in An Introduction to Mocking in
Python. As noted therein, system calls are prime candidates for mocking: whether
writing a script to eject a CD drive, a web server which removes antiquated cache
files from /tmp, or a socket server which binds to a TCP port, these calls all feature
undesired side-effects in the context of unit tests. Similarly, keeping your unit-tests
efficient and performant means keeping as much slow code as possible out of the
automated test runs, namely filesystem and network access.
[Note: This question is for Python developers who are also experienced in Java.]
Q: What are some key differences to bear in mind when coding in Python vs. Java?
Disclaimer #1. The differences between Java and Python are numerous and would
likely be a topic worthy of its own (lengthy) post. Below is just a brief sampling of
some key differences between the two languages.
Disclaimer #2. The intent here is not to launch into a religious battle over the merits
of Python vs. Java (as much fun as that might be!). Rather, the question is really just
geared at seeing how well the developer understands some practical differences
between the two languages. The list below therefore deliberately avoids discussing the
arguable advantages of Python over Java from a programming productivity
perspective.
With the above two disclaimers in mind, here is a sampling of some key differences to
bear in mind when coding in Python vs. Java:

Dynamic vs static typing. One of the biggest differences between the two languages is that
Java is restricted to static typing whereas Python supports dynamic typing of variables.

Static vs. class methods. A static method in Java does not translate to a Python class method.

In Python, calling a class method involves an additional memory allocation that calling a
static method or function does not.

In Java, dotted names (e.g., foo.bar.method) are looked up by the compiler, so at runtime it
really doesnt matter how many of them you have. In Python, however, the lookups occur at
runtime, so each dot counts.
Method overloading. Whereas Java requires explicit specification of multiple same-named
functions with different signatures, the same can be accomplished in Python with a single
function that includes optional arguments with default values if not specified by the caller.

Single vs. double quotes. Whereas the use of single quotes vs. double quotes has significance
in Java, they can be used interchangeably in Python (but no, it wont allow beginnning
the same string with a double quote and trying to end it with a single quote, or vice versa!).

Getters and setters (not!). Getters and setters in Python are superfluous; rather, you should
use the property built-in (thats what its for!). In Python, getters and setters are a waste of
both CPU and programmer time.

Classes are optional. Whereas Java requires every function to be defined in the context of an
enclosing class definition, Python has no such requirement.

Indentation matters in Python. This bites many a newbie Python programmer.

The Big Picture


An expert knowledge of Python extends well beyond the technical minutia of the
language. A Python expert will have an in-depth understanding and appreciation of
Pythons benefits as well as its limitations. Accordingly, here are some sample
questions that can help assess this dimension of a candidates expertise:
Q: What is Python particularly good for? When is using Python the right choice
for a project?
Although likes and dislikes are highly personal, a developer who is worth his or her
salt will highlight features of the Python language that are generally considered
advantageous (which also helps answer the question of what Python is particularly
good for). Some of the more common valid answers to this question include:

Ease of use and ease of refactoring, thanks to the flexibility of Pythons syntax, which makes
it especially useful for rapid prototyping.

More compact code, thanks again to Pythons syntax, along with a wealth of functionallyrich Python libraries (distributed freely with most Python language implementations).

A dynamically-typed and strongly-typed language, offering the rare combination of code


flexibility while at the same time avoiding pesky implicit-type-conversion bugs.

Its free and open source! Need we say more?

With regard to the question of when using Python is the right choice for a project,
the complete answer also depends on a number of issues orthogonal to the language

itself, such as prior technology investment, skill set of the team, and so on. Although
the question as stated above implies interest in a strictly technical answer, a developer
who will raise these additional issues in an interview will always score more points
with me since it indicates an awareness of, and sensitivity to, the bigger picture
(i.e., beyond just the technology being employed). Conversely, a response that Python
is always the right choice is a clear sign of an unsophisticated developer.
Q: What are some drawbacks of the Python language?
For starters, if you know a language well, you know its drawbacks, so responses such
as theres nothing I dont like about it or it has no drawbacks are very telling
indeed.
The two most common valid answers to this question (by no means intended as an
exhaustive list) are:

The Global Interpreter Lock (GIL). CPython (the most common Python implementation) is
not fully thread safe. In order to support multi-threaded Python programs, CPython provides
a global lock that must be held by the current thread before it can safely access Python
objects. As a result, no matter how many threads or processors are present, only one thread is
ever being executed at any given time. In comparison, it is worth noting that the PyPy
implementation discussed earlier in this article provides a stackless mode that supports
micro-threads for massive concurrency.

Execution speed. Python can be slower than compiled languages since it is interpreted. (Well,
sort of. See our earlier discussion on this topic.)

What are the rules for local and global


variables in Python?
If a variable is defined outside function then it is implicitly global. If variable is assigned new
value inside the function means it is local. If we want to make it global we need to explicitly
define it as global. Variable referenced inside the function are implicit global. Following code
snippet will explain further the difference
#!/usr/bin/python
# Filename: variable_localglobal.py
def fun1(a):
print 'a:', a
a= 33;
print 'local a: ', a
a = 100
fun1(a)

print 'a outside fun1:', a


def fun2():
global b
print 'b: ', b
b = 33
print 'global b:', b
b =100
fun2()
print 'b outside fun2', b
------------------------------------------------------Output
$ python variable_localglobal.py
a: 100
local a: 33
a outside fun1: 100
b :100
global b: 33
b outside fun2: 33

Вам также может понравиться