self question

Mike mike at clove.com
Wed Jul 26 14:03:33 EDT 2006


Schüle Daniel wrote:
> Hi all,
>
> given python description below
>
> import random
>
> class Node:
>          def __init__(self):
>                  self.nachbarn = []
>
> class Graph(object):
> 	# more code here
>          def randomizeEdges(self, low=1, high=self.n):
>                  pass
>
>
> graph = Graph(20)
> graph.randomizeEdges(2,5)
>
> I am burned by high=self.n
> quick test with
>
> cnt = 1
> def foo():
> 	global cnt
> 	cnt += 1
> 	return cnt
>
> def bar(x=foo()):
> 	print x
>
> bar()	# 2
> bar()	# 2
> bar()	# 2
>
> this is not behaviour C++ programmer would expect
> does someone know why this kind of behaviour is/was choosen?
>
> Regards, Daniel

I think the answer is that 'def' is an executable statement in python
rather than a definition that the compiler interprets at compile time.

As a result the compiler can evaluate 'foo()' when it defines 'bar', so
it does.

The following works as expected:
def bar():
  print foo()

Hopefully somebody more knowledgable will also respond




More information about the Python-list mailing list