[Tutor] critique my script!

Kent Johnson kent37 at tds.net
Thu Jun 22 03:15:10 CEST 2006

Christopher Spears wrote:
> I can apparently call the functions sometimes without
> ().  Why is that?

There is an important difference between f and f() - f is a reference to 
the function object itself, while f() is a *call* of the function. (Call 
is actually an operator, written (). You can write your own callable 
objects!) Functions are "first-class objects" in Python. That means that 
functions are values. They can be assigned to names, passed to 
functions, stored in data structures, etc. This is very useful in many 
ways, and requires that there be a way to get the function value.

For example, here is a simple function:

In [1]: def f():
    ...:     print 'f here'
    ...:     return 3

Calling f has a side effect - it prints - and it also returns a value - 3.
In [2]: f()
f here
Out[2]: 3

This calls the function and assigns the return value to the variable x.
In [3]: x = f()
f here

In [4]: x
Out[4]: 3

The bare name 'f' is a reference to a function object:
In [5]: f
Out[5]: <function f at 0x00E8CCF0>

This can also be assigned:
In [6]: y = f

Now the name 'y' is a reference to the same function:
In [7]: y
Out[7]: <function f at 0x00E8CCF0>

Calling y is the same as calling f because it refers to the same function.
In [8]: y()
f here
Out[8]: 3

I hope that helps!

In an earlier email you wrote,
> One of my main areas of confusion
> is that I have seemed similar scripts written without
> 'self.button' or 'self.box'.  The programmer simply
> uses 'button' or 'box' instead.

When you write self.button, you are storing the value as an attribute of 
the class instance the method was called on. This attribute will persist 
as long as the instance does (unless you delete it yourself) and can be 
used in other instance method. If you write just button, the value is 
stored in a local variable and will be discarded when the method exits.

For example, here is a simple class:

In [9]: class F(object):
    ...:     def __init__(self, a, b):
    ...:         self.x = a
    ...:         y = b
    ...:     def show(self):
    ...:         print 'F.x =', self.x

In [11]: f=F(1,2)

The parameter passed as a is saved as f.x:
In [12]: f.x
Out[12]: 1

There is no f.y, the variable y only exists within the __init__() method:
In [13]: f.y

D:\<ipython console>

AttributeError: 'F' object has no attribute 'y'

f.x is accessible in other methods:
In [14]: f.show()
F.x = 1

In the case of your original script, you don't refer to any of the 
variables outside __init__(), so there is no reason for them to be 
attributes, they can all be local variables. In general, if you don't 
need the value outside the method, just store it in a local variable.


More information about the Tutor mailing list