class vs function ???

John Roth newsgroups at jhrothjr.com
Sat Feb 21 19:41:41 CET 2004


"Gaurav Veda" <gveda at iitk.ac.in> wrote in message
news:1c764367.0402210857.579f59ab at posting.google.com...
> Hi !
>
> I am a poor mortal who has become terrified of Python. It seems to
> have thrown all the OO concepts out of the window. Penniless, I ask a
> basic question :
> What is the difference between a class and a function in Python ???
> Consider the following code fragments :
> # Fragment 1 begins
>
> a = 1
> print a
> def fun1():
>     global b
>     b = "inside fun1"
>     print b
> fun1()
> def c1():
>     print a
>     print b
>     c = 12
>     def fun2():
>         global d
>         d = "We are dead !!!"
>         print d
>     fun2()
> c1()
> class c2:
>     pass
> print d
> print c
>
> # Fragment 1 ends
> # Fragment 2 begins
> a = 1
> print a
> def fun1():
>     global b
>     b = "inside fun1"
>     print b
> fun1()
> class c1:
>     print a
>     print b
>     c = 12
>     def fun2():
>         global d
>         d = "We are dead !!!"
>         print d
>     fun2()
> class c2:
>     pass
>
> print d
> print c
>
> # Fragment 2 ends
>
> The output of both these codes are precisely the same ! (including the
> error because of 'print c')

Why shouldn't they be the same?

>
> The sample output is :
> 1
> inside fun1
> 1
> inside fun1
> We are dead !!!
> We are dead !!!
> Traceback (most recent call last):
>   File "XYZ.py", line 21, in ?
>     print c
> NameError: name 'c' is not defined
>
> Waiting for some 'logical' explanation !!!


What has probably gotten you confused is that
the text of the class executes when the class is
defined, while the text of a function doesn't.
So in both cases the same statements executed,
but because of a different execution order.

> a = 1
> print a  <------ "1"
> def fun1():
>     global b
>     b = "inside fun1"
>     print b
> fun1()  <--- "inside fun1"
> def c1():
>     print a
>     print b
>     c = 12
>     def fun2():
>         global d
>         d = "We are dead !!!"
>         print d
>     fun2()
> c1() <---- "1", "inside fun1", "We are dead!!!"
> class c2:
>     pass
> print d <----- "we are dead !!!"

> a = 1
> print a  <------ "1"
> def fun1():
>     global b
>     b = "inside fun1"
>     print b
> fun1()  <--- "inside fun1"
> class c1():
>     print a <--- "1"
>     print b <--- "inside fun1"
>     c = 12
>     def fun2():
>         global d
>         d = "We are dead !!!"
>         print d <---- "we are dead !!!"
>     fun2()
> class c2:
>     pass
> print d <----- "we are dead !!!"

John Roth

>
> Gaurav





More information about the Python-list mailing list