2.6. Organizing Python Source Code¶
The rules for when uses Python call by value or call by reference to pass paramters to functions is used are the same as they are in Java. The core built-in data types (int, long, float and string) are all immutable data types and when they are passed to either a function or class methods, call by value is used. When mutable objects are used with class methods, call by reference is used.
>>> # Call by value example >>> def test(x): ... x = x + 2 ... >>> z = 2 >>> test(z) >>> print z 2 >>> # Another call by value example >>> def stest(st): ... st = st + "Hello" ... >>> s = "joe" >>> stest(s) >>> print s joe >>> # Setup for a call by reference example >>> class ctest: ... def __init__(self, n): ... self.n = n ... >>> def c1test(n): ... n.n = n.n + 2 ... >>> x = ctest(5) >>> x.n 5 >>> # Now, x is passed by reference to c1test function. >>> c1test(x) >>> x.n 7
The syntax for defining a Python class is as follows:
Class classname(base_class): optional documentation string static variable declarations method declarations
- Method declarations are just function definitions.
__init__(self, other_args)method is initialization code, not a constructor – subtle point. A
__new__()method may also be declared, which is a constructor. You will not need the
__new__()method for this class.
self.var_nameto reference any class data variables.
- Python features which are not loaded, by default can brought into a Python by importing a module.
foowould be imported using a
import foostatement. This loads the module and evaluates it’s code. Classes and functions from the module are then called with the module name prefixed:
x = foo.bar().
- If we just want to import the
bar()function, we could use the following syntax:
from foo import bar. Now, we could call the
x = bar().
Upon importing a module, the code in the module is evaluated. This means that classes and functions become available since Python knows about them only after they are evaluated. But this also means that any global statements get executed when they are imported.
In simple Python scripts, we often put the code at the global level. This is fine, if the code will never be imported. A better, long term strategy is to put most, or all of the code inside functions and classes and add a statement such as the following at the end of the file:
if __name__ == '__main__': main()
The above statements execute a function called main if the program is run as a stand alone program, but not if it is imported. The global name: __name__ is a built-in name, which is set to ‘__main__’ when the file is executed directly by Python, but is the name of the module when it is imported.