IDLE mini-hack & ? (adding menu items, understanding *args, self)

Greg Ewing greg.ewing at compaq.com
Wed Jul 28 18:33:08 EDT 1999


Isidor wrote:
> 
> One thing I don't really understand here is why it is necessary to
> raise an exception when an argument is passed to a function that
> isn't prepared to handle it.

It isn't strictly necessary, but it helps to catch
errors earlier. Python is so dynamic that there aren't
many opportunities to catch errors until the last
moment, but when there is one, Python takes it.
It's a language design decision, and in my opinion,
it's a good one. The vast majority of the time, passing
the wrong number of arguments to a function is an error.
For the rare cases where it isn't, Python lets you
explicitly say that it's okay.

> My guess is that insert is a method of text, and "insert" (first
> argument) is the location of the insertion point

That's right. To add text to the end of a text widget,
you can use "end" instead of "insert", e.g.

  self.text.insert("end", "something to append")

> a function knows nothing about its context that it isn't told

There are only three sets of names that can be
directly referred to in a function:

(1) Its parameters and local variables
(2) Names defined in the top level of the module where the
    function was defined
(3) Names of built-in Python functions

Note that this does *not* include the parameters and
locals of any *other* function, even if you nest one
function definition inside another. (This surprises people
who are used to languages like Pascal or Scheme.)

In the case of a method, it also doesn't include
any attributes of any class or instance - hence the
need for the "self" argument.

> 2       def funcx(self, *args, **namedargs):
> 3               zip = "googoo"
> 
> 4       def funcy(self, *args, **namedargs):
> 5               print zip
> 
> Something causes me to suspect that this won't work.

You're right, it won't work - whatever you mean
by "work" (it's not clear what you want it to do).

> Can I attach zip to "self" somehow in funcx, e.g., line 3:
> 'self.zip = "googoo"'?

Yes, you can certainly do that. It's the usual way
of assigning to an instance variable in Python.

> Will it only work if self.zip is defined in the
> __init__ func?

No, there's no need to do that. You can add a new
attribute to any instance of any class at any time
just by assigning to it. There is no notion of
"declaring" instance variables.

> "read chap x, sect y of tutorial or language reference").

You might like to read through the chapters of the
language reference dealing with classes and instances.
The principles are really very simple.
Once you have the right mental model of these, you
should be able to answer all those "what will happen
if I do this" questions for yourself.

Hope that helps,
Greg




More information about the Python-list mailing list