[Tutor] silly remedial question
Gregor Lingl
glingl at aon.at
Mon Nov 24 11:37:33 EST 2003
Michael Janssen schrieb:
>On Mon, 24 Nov 2003, kevin parks wrote:
>
>
>
>>I can print the input and output lists no problem, but how do you tell
>>python to print the variable itself..
>>
>>
>
>You can do it for *function* via their __name__ attribute:
>
>def f():
> pass
>
>print f.__name__
>
>
And even this may result in strange effects:
>>> def f():
print "Hi!"
>>> f.__name__
'f'
>>> def f():
print "Hi!"
>>> f()
Hi!
>>> f.__name__
'f'
>>> g = f
>>> g()
Hi!
>>> g.__name__
'f'
>>> del f
>>> f()
Traceback (most recent call last):
File "<pyshell#29>", line 1, in -toplevel-
f()
NameError: name 'f' is not defined
>>> g()
Hi!
>>> g.__name__
'f'
>>>
This is so, because in Python different names can refer to the same object.
So the question "which name refers to this object?" may have no unique
answer.
However there *is* a construct in Python, which can retrieve the string
representation
of names, namely keyword arguments of a function. It goes like this:
>>> def pwn(**kwargs): # print with name
for w in kwargs:
print w, "=", kwargs[w]
>>> a=2
>>> b=5
>>> c=[4,9,11]
>>> pwn(a=a,b=b,c=c,d=[-1,0,1])
a = 2
c = [4, 9, 11]
b = 5
d = [-1, 0, 1]
>>>
This performs more or less automatically what Michael suggested in a
previous post.
The only problem may be, that the order of the output is arbitrary,
except you
implement some sorting routine inside pwn, which is appropriate to your
needs.
Regards,
Gregor
More information about the Tutor
mailing list