Python Objects, Modules, Classes, and Functions


This section is designed to help you understand the basic concepts of objects, modules, classes, and functions in the Python language. This section assumes that you have a basic understanding of object-oriented languages and is designed to provide the information to jump into Python and begin using and creating complex modules and classes.

Using Objects

The Python language is tightly wrapped around the object concept. Every piece of data stored and used in the Python language is an object. Lists, strings, dictionaries, numbers, classes, files, modules, and functions are all objects.

Every object in Python has an identity, a type, and a value. The identity points to the object's location in memory. The type describes the representation of the object to Python (see Table 1.1). The value of the object is simply the data stored inside.

The following example shows how to access the identity, type, and value of an object programmatically using the id(object), type(object), and variable name, respectively:

>>> l = [1,2,3] >>> print id(l) 9267480 >>> print type(l) <type 'list'> >>> print l [1, 2, 3]


After an object is created, the identity and type cannot be changed. If the value can be changed, it is considered a mutable object; if the value cannot be changed, it is considered an immutable object.

Some objects may also have attributes and methods. Attributes are values associated with the object. Methods are callable functions that perform an operation on the object. Attributes and methods of an object can be accessed using the following dot '.' syntax:

>>> class test(object): ...     def printNum(self): ...         print self.num ... >>> t = test() >>> t.num = 4 >>> t.printNum() 4


Using Modules

The entire Python language is built up of modules. These modules are Python files that come from the core modules delivered with the Python language, modules created by third parties that extend the Python language modules that you write yourself. Large applications or libraries that incorporate several modules are typically bundled into packages. Packages allow several modules to be bundled under a single name.

Modules are loaded into a Python program using the import statement. When a module is imported, a namespace for the module, including all objects in the source file, is created; the code in the source file is executed; and a module object with the same name as the source file is created to provide access to the namespace.

There are several different ways to import modules. The following examples illustrate some of the different methods.

Modules can be imported directly using the package or module name. Items in submodules must be accessed explicitly including the full package name.

>>> import os >>> os.path.abspath(".") 'C:\\books\\python'


Modules can be imported directly using the module name, but the namespace should be named something different. Items in submodules must be accessed explicitly including the full package name:

>>> import os as computer >>> computer.path.abspath(".") 'C:\\books\\python'


Modules can be imported using the module name within the package name. Items in submodules must be accessed explicitly including the full package name:

>>> import os.path >>> os.path.abspath(".") 'C:\\books\\python'


Modules can be imported by importing the modules specifically from the package. Items in submodules can be accessed implicitly without the package name:

>>> from os import path >>> path.abspath(".") 'C:\\books\\python'


Note

Python includes a reload(module) function that reloads a module. This can be extremely useful during development if you need to update a module and reload it without terminating your program. However, objects created before the module is reloaded are not updated, so you must be careful in handling those objects.


Understanding Python Classes

Python classes are basically a collection of attributes and methods. Classes are typically used for one of two purposes: to create a whole new user-defined data type or to extend the capabilities of an existing one. This section assumes that you have a fair understanding of classes from C, Java, or other object-oriented language.

In Python, classes are extremely easy to define and instantiate (create new class object). Use the class name(object): statement to define a new class, where the name is your own user-defined object type and the object specifies the Python object from which to inherit.

Note

Class inheritance in Python is similar to that in Java, C, and other object-oriented languages. The methods and attributes of the parent class will be available from the child, and any methods or attributes with the same name in the child will override the parents'.


All code contained in the block following the class statement will be executed each time the class is instantiated. The code sample testClass.py illustrates how to create a basic class in Python. The class statement sets the name of the class type and inherits from the base object class.

Note

The class statement only defines the class object type; it does not create a class object. The class object will still need to be created by calling the class directly.


The __init__() function overrides the method inherited from the object class and will be called when the class is instantiated. The class is instantiated by calling it directly: tc = testCLass("Five"). When the class is called directly, an instance of the class object is returned.

Note

You can specify any necessary parameters to the __init__() function as long as you provide the parameters when calling the class to create a class object.


class testClass(object):     print "Creating New Class\n=================="     number=5     def __init__(self, string):         self.string = string     def printClass(self):         print "Number = %d"% self.number         print "String = %s"% self.string tc = testClass("Five") tc.printClass() tc.number = 10 tc.string = "Ten" tc.printClass()


testClass.py

Creating New Class ================== Number = 5 String = Five Number = 10 String = Ten


Output from testClass.py code.

Note

You need to use the self. prefix inside the class when referencing the attributes and methods of the class. Also, self is listed as the first argument in each of the class methods; however, it does not actually need to be specified when calling the method.


Using Functions

Defining and calling functions in Python is typically pretty easy; however, it can become extremely convoluted. The best thing to keep in mind is that functions are objects in the Python language and the parameters that are passed are really "applied" to the function object.

To create a function, use the def functionname(parameters): statement, and then define the function in the following code block. Once the function has been defined, you can call it by specifying the function name and passing the appropriate parameters.

That being said, the following paragraphs show some of the different ways to accomplish that simple task for the function shown here:

def fun(name, location, year=2006):     print "%s/%s/%d" % (name, location, year)


  • The first example shows the function being called by passing the parameter values in order. Notice that the year parameter has a default value set in the function definition, which means that this parameter can be omitted and the default value will be used.

    >>>fun("Teag", "San Diego") Teag/San Diego/2006

  • The next example shows passing the parameters by name. The advantage of passing parameters by name is that the order in which they appear in the parameter list does not matter.

    >>>fun(location="L.A.", year=2004, name="Caleb" ) Caleb/L.A./2004

  • This example illustrates the ability to mix different methods of passing the parameters. In the example, the first parameter is passed as a value, and the second and third are passed as an assignment.

    >>>fun("Aedan", year=2005, location="London") Aedan/London/2005

  • Parameters can also be passed as a tuple using the * syntax, as shown in this example. The items in the tuple must match the parameters that are expected by the function.

    >>>tuple = ("DaNae", "Paris", 2003) >>>fun(*tuple) DaNae/Paris/2003

  • Parameters can also be passed as a dictionary using the ** syntax, as shown in this example. The entries in the dictionary must match the parameters that are expected by the function.

    >>>dictionary = {'name':'Brendan', 'location':'Orlando', 'year':1999} >>>fun(**dictionary) Brendan/Orlando/1999

  • Values can be returned from functions using the return statement. If a function has no return statement, then a None object is returned. The following example shows a simple square function that accepts a number and returns the square of the number:

    >>> def square(x): ...     return x*x ... >>> print square(3) 9

Note

Functions can be treated as any other Python object. In addition to being called, they can be assigned as a value to a list or dictionary, passed as an argument, returned as a value, and so on.


  • The lambda operator built in to the Python language provides a method to create anonymous functions. This makes it easier to pass simple functions as parameters or assign them to variable names. The lambda operator uses the following syntax to define the function:

    lambda <args> : <expression>

    The term args refers to a list of arguments that get passed to the function. The term expression can be any legal Python expression. The following code shows an example of using the lambda operator to assign an anonymous function to a variable:

    >>>bigger = lambda a, b : a > b >>>print bigger(1,2) False >>>print bigger(2,1) True

Namespaces and Scoping

Scoping in Python revolves around the concept of namespaces. Namespaces are basically dictionaries containing the names and values of the objects within a given scope. There are four basic types of namespaces that you will be dealing with: the global, local, module, and class namespaces.

Global namespaces are created when a program begins execution. The global namespace initially includes built-in information about the module being executed. As new objects are defined in the global namespace scope, they are added to the namespace. The global namespace is accessible from all scopes, as shown in the example where the global value of x is retrieved using globals()["x"].

Note

You can look at the global namespace using the globals() function, which returns a dictionary object that includes all entries in the global namespace.


Local namespaces are created when a function is called. Local namespaces are nested with functions as they are nested. Name lookups begin in the most nested namespace and move out to the global namespaces.

The global statement forces names to be linked to the global namespace rather than to the local namespace. In the sample code, we use the global statement to force the name x to point to the global namespace. When x is changed, the global object will be modified.

Note

Although objects can be seen in outer nested namespaces, only the most local and global namespaces can be modified. In the sample code, the variable b from fun can be referenced for value in the sub function; however, modifying its value in sub would not change the value in fun.


x = 1 def fun(a):     b=3     x=4     def sub(c):         d=b         global x         x = 7         print ("Nested Function\n=================")         print locals()     sub(5)     print ("\nFunction\n=================")     print locals()     print locals()["x"]     print globals()["x"] print ("\nGlobals\n=================") print globals() fun(2)


scope.py

Globals ================= {'x': 1,  '__file__': 'C:\\books\\python\\CH1\\code\\scope.py',  'fun': <function fun at 0x008D7570>,  't': <class '__main__.t'>,  'time': <module 'time' (built-in)>,. . .} Nested Function ================= {'c': 5, 'b': 3, 'd': 3} Function ================= {'a': 2, 'x': 4, 'b': 3, 'sub':     <function sub at 0x008D75F0>} 4 7


Output from scope.py code.

The module namespace is created when a module is imported and the objects within the module are read. The module namespace can be accessed using the .__dict__ attribute of the module object. Objects in the module namespace can be accessed directly using the module name and dot "." syntax. The example shows this by calling the localtime() function of the time module:

>>>import time >>>print time.__dict__ {'ctime': <built-in function ctime>,  'clock': <built-in function clock>,  ... 'localtime': <built-in function localtime>} >>> print time.localtime() (2006, 8, 10, 14, 32, 39, 3, 222, 1)


The class namespace is similar to the module namespace; however, it is created in two parts. The first part is created when the class is defined, and the second part is created when the class is instantiated. The module namespace can also be accessed using the .__dict__ attribute of the class object.

Note

Notice in the sample code that x resides in t.__dict__ and double resides in tClass__dict__, yet both are accessible using the dot syntax of the instantiated class object.


Objects in the class namespace can be accessed directly using the module name and dot "." syntax. The example shows this in the print t.x and t.double() statements:

>>>class tClass(object): >>>    def__init__(self, x): >>>        self.x = x >>>    def double(self): >>>        self.x += self.x >>>t = tClass (5) >>>print t.__dict__ {'x': 5} >>>print tClass.__dict__ {'__module__': '__main__',  'double': <function double at 0x008D7570>, . . . } >>>print t.x 5 >>>t.double() >>>print t.x 5




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net