How to return a simple variable from a function (still newbie) ?

Stef Mientki S.Mientki-nospam at mailbox.kun.nl
Thu Dec 28 13:49:53 EST 2006


Carsten Haese wrote:
> On Thu, 2006-12-28 at 15:28 +0000, Paul Hummer wrote:
>> You'd have to either pass the variables by reference into the function, [...]
> 
> In Python, all function calls are call by reference. Period. The key
> difference between Python and other programming languages is in the
> behavior of the assignment statement.
> 
> To paraphrase http://effbot.org/zone/python-objects.htm :
> 
> In C/C++, assignments modify objects by copying the value from the right
> hand side into the memory allocated to the object on the left hand side.
> 
> In Python, assignments modify namespaces by making the name on the left
> hand side become a reference to the object on the right hand side. It is
> irrelevant whether the name referred to some other object before the
> assignment, and it is irrelevant whether that object is mutable or not.
> 
> The only way to achieve call-by-reference-like behavior in the
> "assignment modifies objects" sense is by passing a reference to a
> mutable object and then invoking the object's methods to mutate it.
> Maybe that's what you meant, but that wasn't clear from what you said.
> 
> -Carsten
> 
> 
Laszlo, Carsten, Paul, Marc,
thanks for your valuable input,
I'm beginning to see the light, but it's still very dimmed.
Not only Python looks much more promising than MatLab,
but the also the Python newsgroup is much more helpfull than ... ;-)

Maybe one of you could give me hint to solve the next problem
(copied from one of my Matlab procedures ;-)
I can find a solution (= something that works) myself,
but I have the feeling this is completely the wrong way to go .

<Python>
# filter a chunk of a continuous signal IOI,
# so a continuous filtered signal is created.
# The function itself returns the filtered signal IOO,
# now to handle the chunks and create a continuous signal
# we must preserve a piece of history: "filter_prev"
# so this should either be an input and output variable

def chunk_Filter (filter_b, filter_a, Signal_IN, filter_prev):
   Extended = r_ [filter_prev, Signal_IN]
   filter_prev = Extended [ len(Signal_IN) : ]
   Extended = signal.lfilter(filter_b, filter_a, Extended)
   Signal_OUT = Extended [ len(filter_prev) : ]
   return Signal_OUT

# call the function with actual parameters

IOO = chunk_Filter (BP_filter_b, BP_filter_a, IOI, BP_filter_prev)
</Python>

When I replace the assignment to "filter_prev", by a loop,
the function works as expected.
<Python>
   #filter_prev = Extended [ len(Signal_IN) : ]
   for i in range( len(filter_prev )):
     filter_prev[i] = Extended [ len(Signal_IN) + i ]
</Python>

I can not use a global variable here, because this function should be 
called for several signals, each of course with it's own history.

thanks,
Stef



More information about the Python-list mailing list