Unification of Methods and Functions

Donn Cave donn at drizzle.com
Sat May 22 14:28:33 EDT 2004


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__."

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.

	Donn



More information about the Python-list mailing list