Importing

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Mar 16 15:31:33 CET 2007


HMS Surprise a écrit :
> Greetings,
> 
> First I will admit I am new to Python but have experience with C++ and
> some Tcl/Tk. I am starting to use a tool called MaxQ that  uses
> jython. I have been studying Rossum's tutorial but still am unclear on
> importing, 

What's your problem here ?

> the use of self,

In Python, a method is a wrapper around a function. This wrappers as a 
reference to the instance on which the method is called, and calls the 
wrapped function passing the instance as first argument. By convention, 
it's named 'self', but technically you could use any other name. So, to 
make a long story short:
  - you need to declare 'self' as the first argument of a method
  - you need to use self to access the current instance within the 
method body
  - you *don't* have to pass the instance when calling the method

> and calling functions with their own name

You mean the
   test = MaxQTest("MaxQTest")
line ?

First point: it's not a function call, it's an object instanciation. 
There's no 'new' keyword in Python, classes are callable objects acting 
as factory for their instances.

Second point: passing the name of the class here is specific to MaxQ, 
and I'd say it's only used for internal and display stuff.

> in quotes. In the code below the lines between #Start and #End are
> generated by browsing web pages. In a large test this section can
> become quite large. The maxQ documentation suggests breaking it up
> into functions. If so could these functions be placed in a separate
> file and imported?

Yes, but you'd have to bind them to the class manually (cf below).

> Is it acceptable to import into a class?

Yes, but this wont solve your problem. Import creates a module object in 
the current namespace, that's all.

> If
> imported as a function will self as used here need to be changed?

Nope.

def quux(self, foo):
   self.bar += foo

class Boo(object):
   def __init__(self, bar):
     self.bar = bar

Boo.quux = quux
b = Boo(40)
b.quux(2)
print b.bar




More information about the Python-list mailing list