Defining class files

Carel Fellinger cfelling at iae.nl
Thu Mar 29 09:18:48 EST 2001


Neil Benn <neil.benn at cambridgeantibody.com> wrote:
> Hello,

>             Sorry to ask such a basic question but -

> I'm wokring through the tutorial and have reached the section on classes in
> Python.  Working through the example on classes I have entered the class
> using the interpreter:-
...
>     I then imported the class, tried to assign the class and ivoke a method

You didn't import the class, you imported the module:)

Modules, classes, packages are python's way to group things.

A module is a file which name ends with ".py".  A module contains
Python statements, e.g. a class statement or an assignment statement.

A package is a directory with a possible empty file named "__init__.py".
Any sensible package contains modules.

The import statement basicly looks for a file with the extension ".py"
[[if there are dots in the import statement like in "import A.B", then
it first looks for a package named "A", and inside that package it
looks for a module file named "B.py"]], it then loads that file,
compiles it and provide access to the goodies of that module through
an module-object.  That module object is normally bound to a var with
the name of that module (without the ".py" ofcourse).

e.g.:

Module file A:

var = 'I am a var'

def f():
   print 'spam'

def class C:
    def f(self):
        print 'more spam'

Some other module, or just from the interactive prompt:

>>> import A
>>> print A.var
I am a var
>>> A.f()
spam
>>> c = A.C()
>>> c.f()
more spam

this will look for a file named "A.py" in your local directory, and if
it can't be found there, iit will search for it in some python specific
directories.  After the impost all goodies are accessible by prefixing
them with "A."

You could also do:

>>> from A import f, C
>>> print var
I am a var
>>> f()
spam
>>> c = C()
>>> c.f()
more spam


Pittfalls to look out for:

In python an assignment is the binding of an object (the right-hand
side) to a name (the left-hand side).  One of the implications of this
is that after a "from import var" var only refers to the value of
A.var at the time of the import. Assigning to A.var or to var won't
change the value of the other.

>>> import A
>>> from A import var
>>> print A.var, var
I am a var I am a var

>>> var = "me too"
>>> print A.var, var
I am a var me too

>>> A.var = "all's swell"
>>> print A.var, var
all's swell me too
-- 
groetjes, carel



More information about the Python-list mailing list