Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
 
Python Calling functions and methods. Using objects and modules.

The whole ethos of Python is about code reuse. About not re-inventing the wheel if someone else has already invented the wheel, and indeed about adapting their wheels if they're not quite what you need. This module, then, covers code reuse.

Builtins

There are between 100 and 150 built in objects in Python when you start an interpretter (remember that everyting is an object in Python) and about a half of those are built in functions.

PASSING PARAMETERS AND RETURNING VALUES

You call a builtin function by name, and in brackets after the name you place any values that you're passing in to the function. A function will normally return a resulting value to you, and that values may be assigned to a variable of used within an expression (or have a method run on it).

For example:

Sample = "It's a long way to Tipperary"
syze = len(Sample)
print "The length of \"",Sample,"\" is",syze,"characters"

sequence = range(1,21,2)
addedup = sum(sequence)
print "sequence is",sequence,"which sums to",addedup

Which runs as follows:

wizard:y200.d graham$ python biff
The length of " It's a long way to Tipperary " is 28 characters
sequence is [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] which sums to 100
wizard:y200.d graham$

You'll already have seen some other built in functions in use in your very early Python examples on this course - input and raw_input, for example, and we'll introduce you to more of the as the course goes on. There's even a built in function called dir which lets you see what names (including functions) you have loaded into a particular area, and if you use

dir(__builtins__)

from the interactive command line, you'll get a full list of the builtins. Please don't try and learn about all of them; many are pretty esoteric and you're unlikely to ever need them. But here's the current (Python 2.7) list:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

Methods on built in data types

Built in functions are wide ranging, and operate at all levels of Python. Built in methods are functions which operate on a particular type of variable only, and the syntax is different.

days = ["Monday","Tuesday","Wednesday"]

r1 = len(days)
r2 = days.count("Tuesday")
r3 = days.count("Thursday")

print r1,r2,r3

which runs as follows

wizard:y200.d graham$ python lenco
3 1 0
wizard:y200.d graham$

Note - you can use "len" on anything, but this version of "count" is specific to a list

Methods often make changes to the object on which the method is run, so it's not uncommon for there to be no return value

days = ["Monday","Wednesday"]
days.append("Friday")
print days

Modules

Some functionallity - such as lists and strings themselves and many of the opertions we have performed on them - are needed so often that they're loaded by default into every Python program that you run. But other functionallity is less commonly required - it's needed commonly enough to be distributed with Python, perhaps, but not so commonly as to be loaded into (and therefore clutter up, add to the footprint of, and slow down) every Python program.

This extra functionallity is available to you as modules (you'll learn about packages of modules later).

LOADING AND CALLING

You can load in module in 2 different ways - using <b>from</b> or using <b>import</b>

With from, all the names that you load in become a part of the namespace (familiy) that you're working within - so the extra names are then quickly and easily available to you. This has the advantage that they can be called up by a very short piece of code, but the disadvantage that they'll overwrite anything else that's already loaded with the same name.

from os import *

contains = listdir(".")
print contains

With import, the names are brought into their own namespace (family) and so there's no risk of them overwriting anything else. Its also clearer when the calling program references them as to their source, but if you're making lots of calls to them, it can get rather repetitive.

import os

contains = os.listdir(".")
print contains

Those examples run as follows:

wizard:y200.d graham$ python fromlist
['appy', 'biff', 'fromlist', 'importlist', 'lenco']
wizard:y200.d graham$ python importlist
['appy', 'biff', 'fromlist', 'importlist', 'lenco']
wizard:y200.d graham$

With both from and import, the from or import statement are performed at run time, and part of the action of loading is to run the code that's within the module. That means that you can conditionally load something if you wish, and that you could even repeatedly load it within a loop. This latter is not recommeneded under normal circumstances, but is is interesting to note that you can replace modules, methods and functions while your program is running, which is not a feature commonly shared with other languages.

Both from and import have their problems - neither is ideal for all circumastances, which is why you have both.
- With from, you can limit which names are loaded in order to only overwrite / provide the elements you want in your code. e.g.
 from os import listdir
- With import, you can add as "as" clause to rename the module as you load it to something shorter.
 import numpy as np
is very common.

LEARNING

How do you find out what's available?

- There's a global module index at http://docs.python.org/modindex.html
- From there you can link to the manual page which tells you more about it
- You can also import it into an interactive Python shell and use
 dir(xxxx)
and then __doc__ on the module as a whole and to its individual object members

From the long list, the following are ones that we use most during courses ...

- cgi - common gateway interface to the web
- copy - deep copy of an object
- Cpickle and pickle - serialising an object
- cProfile and profile - code profiler - what's been used how many times
- doctest - code testing module to check it does what it says on the tin
- ftplib - FTP client
- getopt - handling command line options
- HTMLParser - parsing HTML and XML
- httplib - HTTP and HTTPS clients
- json - handling json format data
- keyword - checking whether a word is a Python keywork
- marshall - serialising a sinmple object
- math - maths functions (trig, log, etc)
- os - Operating system dependent function
- os.path - Operating System function which have path (/ and \) dependecies
- popen2 - running a parallel process and piping from / to it
- pydoc - python documentation handler
- random - random number, shuffle, etc
- re - regular expressions
- shelve - storing and retreiving serialised objects
- socket - network protocol low level handlers (used by other modules)
- sys - system values - "interfacing to the main computer"
- tempfile - handling temporaru files
- time - date and time functions
- timeit - monitoring the performance of a chunk of code
- Tkinter - The Tk Graphic User Interface
- unittest - regression testing
- urllib - handling web pages from a Python program
- urllib2 - handling web pages from a Python program (version 2)

And these are some of the modules which we most often load in addition to the standard

- matplotlib - plotting and graphing
- numpy - numerical data type handler - Python wrapper to C functionallity
- scipy - scientific calculations on to of numpy
- pyplot - Python Plot library
- networkx - data set manipulation

OPTIONAL AND KEYWORD PARAMETERS, GLOBALS, PROPERTIES AND STATICS.

There is more flexibilty in calling sequences to functions and methds that the ones we have introduced in this module. So far, all the parameters we have show you have been mandarory, and position dependent. However, there are two other types of paramaters too

1. You may have OPTIONAL parameters. There always come after mandatory parameters. They are still positional, but if nor specified then the function / method will take a default value. Note that you may not write ,, in your calling sequence to leave out an intermediate parameter, so it's up to the designer who uses optional parameters to put the most optional on the end.

2. You may also call with named parameters - that's where you pass in parameters with specific names which the method called will recognise.

Here's an example showing what these calls may look like:

import taxcalcs as tc

amount = float(raw_input("How much did you spend? "))

net = tc.getnet(amount,25,country="Denmark",comment="demo",type="VAT",another=tc.gettax)
print "That was",net,"for the merchant (Denmark)"

net = tc.getnet(amount,country="Slovenia",taxrate=20,year=2008,type="VAT")
print "That was",net,"for the merchant (Slovenia)"

print tc.copyright

The reference to tc.copyright is a PROPERTY - a variable within an object than can be read and written. Properties (and attributes) have some use and are covered later on the course.

You may occasionally find that a function or method uses a global variable. That's a variable who's name you are told which you must set before calling a function or method, or which mysteriously turns up after you have completed the running of a function or method. These are occasionally useful, but caution is strongly advised; they provide you with a very tempting way to write code which is very hard indeed to maintain or reuse.




See also Python Programming course

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Python - using functions, objects and modules.
  [4719] Nesting decorators - (2016-11-02)
  [4438] Loving programming in Python - and ready to teach YOU how - (2015-02-22)
  [418] Difference between import and from in Python - (2005-08-18)

Python - Functions, Modules and Packages
  [4724] From and Import in Python - where is the module loaded from? - (2016-11-06)
  [4722] Embedding more complex code into a named block - (2016-11-04)
  [4719] Nesting decorators - (2016-11-02)
  [4662] Recursion in Python - the classic example - (2016-03-07)
  [4645] What are callbacks? Why use them? An example in Python - (2016-02-11)
  [4448] What is the difference between a function and a method? - (2015-03-04)
  [4441] Reading command line parameters in Python - (2015-02-23)
  [4410] A good example of recursion - a real use in Python - (2015-02-01)
  [4407] Python - even named code blocks are objects - (2015-01-28)
  [4361] Multiple yields and no loops in a Python generator? - (2014-12-22)
  [4212] Python functions - an introduction to how they work - (2013-11-16)
  [4161] Python varables - checking existance, and call by name or by value? - (2013-08-27)
  [4029] Exception, Lambda, Generator, Slice, Dict - examples in one Python program - (2013-03-04)
  [3945] vargs in Python - how to call a method with unknown number of parameters - (2012-12-06)
  [3931] Optional positional and named parameters in Python - (2012-11-23)
  [3885] Default local - a good choice by the author of Python - (2012-10-08)
  [3852] Static variables in Python? - (2012-08-29)
  [3766] Python timing - when to use a list, and when to use a generator - (2012-06-16)
  [3695] Functions are first class variables in Lua and Python - (2012-04-13)
  [3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)
  [3474] Python Packages - groupings of modules. An introduction - (2011-10-11)
  [3472] Static variables in functions - and better ways using objects - (2011-10-10)
  [3464] Passing optional and named parameters to python methods - (2011-10-04)
  [3459] Catching the fishes first? - (2011-09-27)
  [3280] Passing parameters to Python functions - the options you have - (2011-05-07)
  [3159] Returning multiple values from a function call in various languages - a comparison - (2011-02-06)
  [2998] Using an exception to initialise a static variable in a Python function / method - (2010-10-13)
  [2994] Python - some common questions answered in code examples - (2010-10-10)
  [2929] Passing a variable number of parameters in to a function / method - (2010-08-20)
  [2878] Program for reliability and efficiency - do not duplicate, but rather share and re-use - (2010-07-19)
  [2766] Optional and named parameters to Python functions/methods - (2010-05-15)
  [2718] Python - access to variables in the outer scope - (2010-04-12)
  [2520] Global and Enable - two misused words! - (2009-11-30)
  [2506] Good example of recursion in Python - analyse an RSS feed - (2009-11-18)
  [2481] Sample code with errors in it on our web site - (2009-10-29)
  [2440] Optional parameters to Python functions - (2009-10-07)
  [2439] Multiple returns from a function in Python - (2009-10-06)
  [2011] Conversion of OSI grid references to Eastings and Northings - (2009-01-28)
  [1879] Dynamic code - Python - (2008-11-11)
  [1871] Optional and named parameters in Python - (2008-11-05)
  [1870] What to do with a huge crop of apples - (2008-11-04)
  [1869] Anonymous functions (lambdas) and map in Python - (2008-11-04)
  [1790] Sharing variables with functions, but keeping them local too - Python - (2008-09-09)
  [1784] Global - Tcl, PHP, Python - (2008-09-03)
  [1464] Python Script - easy examples of lots of basics - (2007-12-08)
  [1202] Returning multiple values from a function (Perl, PHP, Python) - (2007-05-24)
  [1163] A better alternative to cutting and pasting code - (2007-04-26)
  [1134] Function / method parameters with * and ** in Python - (2007-04-04)
  [959] It's the 1st, not the 1nd 1rd or 1th. - (2006-12-01)
  [949] Sludge off the mountain, and Python and PHP - (2006-11-27)
  [913] Python - A list of methods - (2006-11-03)
  [912] Recursion in Python - (2006-11-02)
  [900] Python - function v method - (2006-10-20)
  [821] Dynamic functions and names - Python - (2006-08-03)
  [775] Do not duplicate your code - (2006-06-23)
  [749] Cottage industry or production line data handling methods - (2006-06-07)
  [745] Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. - (2006-06-05)
  [668] Python - block insets help with documentation - (2006-04-04)
  [561] Python's Generator functions - (2006-01-11)
  [418] Difference between import and from in Python - (2005-08-18)
  [386] What is a callback? - (2005-07-22)
  [340] Code and code maintainance efficiency - (2005-06-08)
  [308] Call by name v call by value - (2005-05-11)
  [303] Lambdas in Python - (2005-05-06)
  [294] Python generator functions, lambdas, and iterators - (2005-04-28)
  [105] Distance Learning - (2004-10-31)
  [96] Variable Scope - (2004-10-22)

Object Oriented Python
  [4721] When to check an object type - Python isinstance example - (2016-11-03)
  [4650] Why populate object with values as you construct them? - (2016-02-18)
  [4591] From single block to structure and object oriented programming - (2015-12-02)
  [4448] What is the difference between a function and a method? - (2015-03-04)
  [4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
  [4028] Really Simple Class and Inheritance example in Python - (2013-03-04)
  [4021] Spike solution, refactored and reusable, Python - Example - (2013-02-28)
  [3947] this or self - what are they, and what is the difference? (Python) - (2012-12-08)
  [3878] From Structured to Object Oriented Programming. - (2012-10-02)
  [3673] Object oriented or structured - a comparison in Python. Also writing clean regular expressions - (2012-03-26)
  [3436] Moving from scripting to Object Orientation in Python - (2011-09-13)
  [3399] From fish, loaves and apples to money, plastic cards and BACS (Perl references explained) - (2011-08-20)
  [3085] Object Oriented Programming for Structured Programmers - conversion training - (2010-12-14)
  [2604] Tips for writing a test program (Ruby / Python / Java) - (2010-01-29)
  [2169] When should I use OO techniques? - (2009-05-11)
  [2017] Python - a truly dynamic language - (2009-01-30)
  [1925] Introduction to Object Oriented Programming - (2008-12-06)
  [1348] Screw it or Glue it? Access to Object variables - a warning - (2007-09-12)
  [1306] Python class rattling around - (2007-08-16)
  [900] Python - function v method - (2006-10-20)
  [834] Python makes University Challenge - (2006-08-15)
  [477] Class, static and unbound variables - (2005-10-25)

resource index - Python
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2019: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/python-p ... dules.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard