Unification of Methods and Functions

David MacQuigg dmq at gain.com
Sat May 22 15:02:06 EDT 2004


On Sat, 22 May 2004 18:28:33 -0000, "Donn Cave" <donn at drizzle.com>
wrote:

>Quoth David MacQuigg <dmq at gain.com>:
>| import math
>|
>| def mypow(x, y):
>|       return x**y
>|
>| class MathA:
>|    pow = math.pow
>|
>| class MathB:
>|    pow = mypow
>|
>| ma = MathA()
>| mb = MathB()
>|
>| print ma.pow(2,4) #=>
>| 16.0
>| print mb.pow(2,4) #=>
>| # TypeError: mypow() takes exactly 2 arguments (3 given)
>|
>| How would you explain this to non-CIS students in a class on circuit
>| design, where there is very little time to discuss programming?
>
>I wouldn't.  I would say
>
>  "Classes allow you to create objects with their own functions,
>   called methods, that you write.  Each function takes `self'
>   as its first parameter."
>
>  "Here's a class:"
>    class A:
>         def __init__(self):
>             self.data = 'spud'
>         def hello(self):
>             print 'Hello, I am a class A', self.data
>
>  "Classes can inherit functions from other classes:"
>    class B(A):
>         def __init__(self):
>             self.data = 'gerbil'
>
>  "The actual object - a class `instance' - is created by invoking
>  the class name, applying arguments which will be passed to __init__."

This is OK for the first example.  I would leave the __init__ methods
to the second example, but either way it will take about 8 pages to
comfortably explain OOP ( maybe ten if I include the "robust
programming" examples that JM says I must ).  I would like students to
understand Python at the level they can follow what is going on in a
real program, and maybe write a few classes themselves.

>Then I would go over that, showing what happens and why, until the
>concepts introduced above seem to be clear for everyone.  That would
>conclude my treatment of classes.  As an elementary language, there
>are some slightly hard things to learn about Python, but this isn't
>going to be one of them unless you make it hard.

If you are saying we can totally ignore the different method forms, I
think you are wrong.  Bound and unbound methods, for example, will be
needed in almost any sizable program.  The need for static methods
will arise when the student first writes a method that needs to work
without a current instance.

The example I showed is not intended to explain method binding, and I
would not use it in an introduction to OOP.  It probably won't even be
"stumbled upon" in a normal program.  I posted it only to show that
even experts can get confused by Python's binding syntax.  Are you not
confused by this example?

-- Dave




More information about the Python-list mailing list