473,397 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

self question

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
Jul 25 '06 #1
6 1327
cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=foo()):
print x

bar() # 2
bar() # 2
bar() # 2
Looks to me like you want to use the following programming pattern to
get dynamic default arguments:

cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=None):
if x is None:
x = foo()
print x

bar() # 2
bar() # 3
bar() # 4

Jul 25 '06 #2
da******@gmail.com schrieb:
>cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=foo()):
print x

bar() # 2
bar() # 2
bar() # 2

Looks to me like you want to use the following programming pattern to
get dynamic default arguments:

cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=None):
if x is None:
x = foo()
print x

bar() # 2
bar() # 3
bar() # 4
yes, I haven't thought of that
nowI changed my class to

class Graph:
settings = {
"NumNodes" : 10,
"MinNodes" : 2,
"MaxNodes" : 5
}
def randomizeEdges(self,
lowhigh = (settings["MinNodes"], settings["MaxNodes"])):
low, high = lowhigh
for node in self.nodes:
x = random.randint(low, high)
# link the nodes
maybe the only minor point is that no relationship
can be expressed

settings = {
"NumNode" : 10,
"MinNode" : settings["NumNode"] / 2,
"MaxNode" : settings["NumNode"]
}

but I think the solution is nevertheless ok
Regards, Daniel
Jul 25 '06 #3
correction :)
class Graph:
settings = {
"NumNodes" : 10,
"MinNodes" : 2,
"MaxNodes" : 5
}
def randomizeEdges(self,
lowhigh = (settings["MinNodes"], settings["MaxNodes"])):
of course this should be
Graph.settings["MinNodes"], Graph.settings["MaxNodes"])
Jul 25 '06 #4
On Tue, Jul 25, 2006 at 08:08:32PM +0200, Sch?le Daniel wrote:
da******@gmail.com schrieb:
cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=foo()):
print x

bar() # 2
bar() # 2
bar() # 2
Looks to me like you want to use the following programming pattern to
get dynamic default arguments:

cnt = 1
def foo():
global cnt
cnt += 1
return cnt

def bar(x=None):
if x is None:
x = foo()
print x

bar() # 2
bar() # 3
bar() # 4

yes, I haven't thought of that
nowI changed my class to

class Graph:
settings = {
"NumNodes" : 10,
"MinNodes" : 2,
"MaxNodes" : 5
}
def randomizeEdges(self,
lowhigh = (settings["MinNodes"], settings["MaxNodes"])):
Note that this is a change in behaviour from what you originally stated you
wanted. settings is a dictionary that is shared between all instances of
Graph. The previous poster was suggesting the correct pattern for the
behaviour you requested. Generally if you want a parameter to have a dynamic
default argument you set the default value to None, test for None in the body
of the function/method and set the value appropriately.
low, high = lowhigh
for node in self.nodes:
x = random.randint(low, high)
# link the nodes
maybe the only minor point is that no relationship
can be expressed

settings = {
"NumNode" : 10,
"MinNode" : settings["NumNode"] / 2,
"MaxNode" : settings["NumNode"]
}

but I think the solution is nevertheless ok
Regards, Daniel
--
http://mail.python.org/mailman/listinfo/python-list
Jul 26 '06 #5

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

Jul 26 '06 #6
Mike wrote:
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
The def statement is, as you say, an executable statement. It creates a new
function object, so it is quite useful to look directly at the function
type to see what arguments its constructor takes:
>>import types
help(types.FunctionType)
Help on class function in module __builtin__:

class function(object)
| function(code, globals[, name[, argdefs[, closure]]])
|
| Create a function object from a code object and a dictionary.
| The optional name string overrides the name from the code object.
| The optional argdefs tuple specifies the default argument values.
| The optional closure tuple supplies the bindings for free variables.
....

The arguments passed to the constructor when the def statement is executed
are:

a code object. This object is created once when the module containing the
function is compiled. The def doesn't have to do anything with the actual
code, so it will take the same time whether you def a function of 1 line or
1000 lines.

globals is the same value as you get by calling the builtin globals().

name is the function name. It's a string constant.

argdefs is the interesting one here. It is a tuple of the default argument
values and is created every time the def statement is executed.

closure is another tuple which is created every time the def statement is
executed. This allows a def nested inside another function to reference the
current local variables which are in scope when the def executes. This
tuple can only contain cell objects which are an internal object type used
for scoped variables.

So, argdefs and closure are the two things which are different each time
you def a function, everything else is constant and shared between
definitions of the same function.
Jul 27 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jim Jewett | last post by:
Normally, I expect a subclass to act in a manner consistent with its Base classes. In particular, I don't expect to *lose* any functionality, unless that was the whole point of the subclass. ...
4
by: Raymond Wilk | last post by:
I used javascript to open a new window, then used the following to close the new window on the next click: <body onBlur="self.close()" onClick="self.close()" bgcolor="#FFFFFF"> On the new window...
0
by: falcon | last post by:
Hello python-list, As I Understood, semantic may be next: def qwerty(a,a.i,b,b.i,f.j): pass Would work like: def qwerty(anonymous1,anonymous2,anonymous3,anonymous4,anonymous5):
1
by: Adam Monsen | last post by:
Is there anything wrong with using something like super(type(self), self).f() to avoid having to hardcode a type? For example: class A(object): def f(self): print "in A.f()" class B(A): def...
24
by: Richard Aubin | last post by:
I'm really new to vb.net programming and programming in general. I would like to teach myself on how to program effectively and I have the financial and time resources to do so. Can I anyone...
7
by: Andrew Robert | last post by:
Hi Everyone, I am having a problem with a class and hope you can help. When I try to use the class listed below, I get the statement that self is not defined. test=TriggerMessage(data) var...
14
by: Gert Cuykens | last post by:
Is there a difference between <code> class HelloWorld: def index(self): index.exposed = True return "Hello world!" </code> and
5
by: openopt | last post by:
I have class A: def __init__(self, objFun, x0): #(I want to have self.primal.f = objFun) #both self.primal.f = objFun #and self.primal = None self.primal.f = objFun
8
by: ssecorp | last post by:
I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am...
4
by: harijay | last post by:
Hi I am new to writing module and object oriented python code. I am trying to understand namespaces and classes in python. I have the following test case given in three files runner , master and...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.