class or function

Michele Simionato michele.simionato at poste.it
Thu Feb 5 05:01:03 EST 2004


Bart Nessux <bart_nessux at hotmail.com> wrote in message news:<bvr58r$h1e$1 at solaris.cc.vt.edu>...
> What is the significant difference between using a class, like this:
> 
> class threaded_ddos(Thread):
>     def run(self):
>        pass
> if __name__ == '__main__':
> 
> Or, using functions, like this:
> 
> def threaded_ddos(Thread):
>     def run():
>        pass
>     run()
> threaded_ddos()
> 
> I'm trying to better understand this difference. I tend to use functions 
> that call functions instead of classes that contain functions which I 
> can import. To me, functions within functions are simpler. The results 
> of either method are the same, but I must ask which is preferred and 
> why? Are both OK depending on the application? I don't do inheritance 
> type stuff.

Using functions inside functions is somewhat less pythonic than using a
class. 

Argument 1: if I use I class, I get for free all the goodies
of Python introspection. For instance, I can get the list of defined
methods, whereas I cannot get the list of inner functions in a nested 
function. pydoc is happier with classes than with functions.

Argument 2: if I use a clas I can easily change attributes, whereas 
nested functions cannot modify variables in outer scope (unless I use 
dirty tricks such as putting the variables to be modified in a list).

Argument 3: Guido thinks that the obvious way to do things is with classes
and methods and not with nested functions (I infer this from the fact
that Python didn't have nested scopes till 2.1).

So, you can use nested functions in Python, but the language
is not intended for this and there are better alternative, even if
you don't use inheritance. So, my Python code contains few nested 
functions. On the other hand, my Scheme code is full of nested functions ;)

    Michele Simionato



More information about the Python-list mailing list