class vs function ???

Josiah Carlson jcarlson at nospam.uci.edu
Sat Feb 21 13:15:07 EST 2004


Python allows you to do basically whatever you want, that doesn't mean 
that what you do makes sense.

There are cases where embedding functions is useful (you don't want that 
function available to everything else in the module), but it doesn't 
help with data abstraction, which is the fundamental use of classes:

 >>> class blah:
...     def __init__(self, embed):
...         self.embedded = embed
...     def print_embedded(self):
...         print self.embedded
...
 >>> a = blah(5)
 >>> a.print_embedded()
5

To do this with embedded functions, you'd need to add an attribute to 
some returned object explicitly.

 >>> def blah2(embed):
...     def print_embedded():
...         print embed
...     print_embedded.print_embedded = print_embedded
...     return print_embedded
...
 >>> b = blah2(6)
 >>> b.print_embedded()
6


Now, the above works, but in my opinion, is ugly.  I suggest you try to 
do the following with embedded functions (it can be done, but is ugly):

class blah3:
     pass
c = blah3()
c.hello = 1
c.goodbye = 2
del c.hello
print c.goodbye


 > What is the difference between a class and a function in Python ???

Functionally, you can do the same with both.  Pragmatically, classes are 
easier to use for all non-trivial data abstraction.  I know my 
explanation hasn't been very good, but you really haven't looked at much 
Python code if you don't understand the difference between functions and 
classes.

  - Josiah



More information about the Python-list mailing list