class vs function ???

Paul Prescod paul at
Sun Feb 22 08:06:14 CET 2004

Gaurav Veda wrote:

> Hi !
> I have read all the replies and they are all extremely helpful. Thanks
> a lot !!!
> My basic doubts were :
> 1) I am allowed to write things in the class body without the need for
> encapsulating them in functions. Moreover, they are executed as soon
> as I define the class. Infact, I can also call functions in the class
> body (the way  I called fun2). All this, while I am just defining the
> class !	-- I still don't understand why are classes implemented in
> this way in pyhton.

In Python, function declarations ("def"s) are statements just like "if" 
or "print" or "while". Anywhere you can define a function you can use 
"if" or "print" or "while" and anywhere you can use "if" or "print" or 
"while", you can use "def". This simplifies the language by removing 
special cases. This basic concept is also very powerful sometimes:

class do_somethin_in_a_cross_platform_way:
     if sys.platform=="win32":
         import some_win32_library
         def myfunc():
         import some_unix_library
         def myfunc():

For various reasons you are unlikely to see code that looks exactly like 
that but you should get the gist of how you can take advantage of 
Python's flexibility. Here's another kind of pattern that may stretch 
your mind:

def function_that_makes_functions(arg1):
    def inner_function(self, arg2):
        ... do something with arg1 and arg2 ...

    return inner_function

class a:
    mymethod1 = function_that_makes_functions("abc")
    mymethod2 = function_that_makes_functions("def")

> ...
> Being a 3rd year undergraduate student, I have to make a Python
> 'compiler' (I know it sounds foolish -- but thats what my instructor
> wants me to do !).

There are actually a few Python compilers out there. 
compiles to Python bytecodes. Pyrex compiles to C. Jython compiles to 
Java bytecodes. There are couple of half-implemented compilers to .NET 

You probably need to define a subset as Pyrex does. Compiling all of 
Python is quite a challenge and won't teach you much about how people 
compile more traditional languages like Java or C.

  Paul Prescod

More information about the Python-list mailing list