[Tutor] Defining a function (Joseph Q.)

Brian van den Broek bvande at po-box.mcgill.ca
Tue Apr 12 18:08:02 CEST 2005


Joseph Quigley said unto the world upon 2005-04-11 20:23:
> Well, now I've learned what def is good for. But what could I put in the 
> parenthesis of  def foo():?
> Of course self is always available, but what would maybe def 
> foo(number1): do? An error right? So I now repeat my self, what else 
> besides self could I put in there?
> 
> Thanks,
>         Joseph

Hi Joseph,

as Liam explained, you put the arguments (if any) to the function in
the parenthesis.

But, I want to address the bit where you said "Of course self is
always available". *Any* valid Python identifier (or name) can be used
("is always available"):

>>> def silly(a_name_I_picked_at_random):   # well, not quite
... 	print a_name_I_picked_at_random     # at random ;-)
... 	
>>> silly(42)
42

The name a_name_I_picked_at_random is like a "placeholder" inside the
function for whatever input we gave to the function. And *that* can be
any object:

>>> silly(silly)
<function silly at 0x01298070>
>>>

Some functions require certain sorts of inputs in virtue of what they
try to do with them, but we can still pass any sort of object in.  For
instance, Liam had:

>>> def foo(a, b):
... 	return a + b
...

Now, try this:

>>> foo(42, '42')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 2, in foo
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

That's not a problem with Liam's function; it's a problem that I
caused by sending it inappropriate inputs.


At any rate, you are correct that you can always name an argument
"self". But "self" is, by *very* strong convention, used only within
classes.  Simplifying[*] a bit, a method is a function defined
internal to a class. If you define a method in a class, you call the
first argument of the method definition "self", and it is
automatically interpreted as a reference to the `active' instance of
the class on which the method is called.

So, don't use "self" outside of method definitions. You can ("we are
all adults here"), but doing so will only confuse things given the
strength of the convention.

[*] The simplification comes in that not all methods in a class need
to be bound to an instance, so not all methods employ "self". But, my
guess is that is something you shouldn't be worrying about just yet.

Best,

Brian vdB




More information about the Tutor mailing list