Episode 1 dealt with a Python setup in a XAMPP environment. So how does Python compare to PHP in a web application? Rather than relearning how to code here is a list of key elements in Python that are different from PHP.

Modules

Instead of including a script as include(‘main.php’), Python uses modules as in import main (importing main.py but without the extension). There is also a library of standard modules. Examples are datetime and email. Sometimes the module to use depends on the framework. For example collecting a $_POST (in PHP) variable requires the cgi module when running Python in cgi mode. With Django the request module handles form data.

Error reporting

In the code below line 1 gives the location of the Python executable ( in this environment it should be C:\Python34\python.exe) Line 2 imports the cgitb module (Traceback manager for CGI scripts) and line 3 switches on the error reporting. Python does not have a error reporting level concept.

#!/Python34/python
import cgitb
cgitb.enable()

Content type

For creating HTML pages stating the content type is mandatory. If omitted, the Python print() function defaults to the PHP htmlspecialchars() function

#!/Python34/python
# the output is html (mandatory)
print("Content-Type: text/html\n\n")

print("Hello world!")

Variables

Variables are not preceded by a dollar sign and statements do not require a closing semicolon. Good thinking! It is unfortunately not possible to embed Python in HTML necessitating the use of template engines.

a = "hi there"
print(a)

Objects

Everything is an object. Integers are objects: (1).__add__(2) equals 3. The methods available for the integer 1 can be found with dir(1) as an array. Same story for strings:

a = 'big';
# prints ['__len__'] as a magic method
print(dir(a));
# the output is 3
print(len(a))
print((a).__len__())

# regular method
print(a.upper())


Needless to say in PHP integers and strings are not objects.

Magic methods

Just as in PHP , Python works magic methods but there are differences. In PHP all nine magic methods (starting with a double underscore) are called indirectly. For example the __construct() magic method is called at instantiation of a new object. In Python a lot more magic methods exist (now surrounded by double underscores). The __construct() equivalent is __init__()

Magic methods can also be called directly: abs(-10) and (-10).__abs__() both results in 10. In fact every call to abs() results in a behind-the-scenes __abs__() call.

Array types

In PHP an array is an ordered map and by default associative although keys are optional. In Python we have several array types: lists, tuples, sets and dictionaries. Lists are of the type a = [1,2,5,5] containing just values. This data structure type is again an object with available methods such as pop() and sort(). The count() function does not do what you would expect: a.count(5) gives the number of occurrences of 5. Tuples are similar to lists but they are immutable. It basically means that methods such as pop() are absent. A set is an array that does not allow duplicate elements: they are automatically removed.

# tuples
t = ('a', 'b');
# equivalent to 
t = 'a','b'

# A set
set = {1,2,3,5,4,3}
# outputs {1, 2, 3, 4, 5} with duplicates removed
print(set)

Mercifully a dictionary is the regular associative array. Want more arrays? Array is also a specific module for data collections of a single type:

from array import *
# i stands signed integer of size 1 byte
a = array('i',[1,2,3,4])
#prints 3
print(a[2])
# B = unsigned integer of size 1 byte
a = array('B',[1,2,-3,4])
# OverflowError: unsigned byte integer is less than minimum

Strings

Strings are immutable, just as tuples but with a difference, you can still concatenate strings but the id associated with the string will change.

s = 'a'
print(id(s)) 
# prints 34514456
s = s + "b"
print(id(s)) 
# prints 38058952
print(s) 
# prints ab


So it is more of a behind-the-scenes thing.

Functions

The basic function implementation looks like this:

def Hi():
    return "hi"

print(Hi())

Def is short for define. The indentations are mandatory, ignore it will get you a “IndentationError: expected an indented block” in your face. PHP developers will be shocked to learn that functions accept global variables by default. fortunately variables declared globally can be overwritten locally and local variables cannot escape out into the open.

b = 6
def sum(a):    
    a = a + b
    return a
a = 1;
# prints 7
print(sum(a))

Classes

All class methods have as first argument the class itself as self. Use the __init__ function for instantiation.

class Arith():
    c = 3
 
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def sum(self):
        return self.a + self.b

    def multiply(self):
        return self.a * self.b

arith = Arith(2,3)
sum = arith.sum()
#prints 5
print(sum)
multiply = arith.multiply()
#prints 6
print(multiply)

Multiple inheritance is allowed making PHP devs no-doubt green with jealousy.

Links

* http://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python
* http://www.rafekettler.com/magicmethods.html
* http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
* http://www.thegeekstuff.com/2013/08/python-array/
* https://en.wikibooks.org/wiki/Non-Programmer’s_Tutorial_for_Python_3/Defining_Functions

Advertisements