Please explain this python behavior
class SomeClass(object):
def __init__(self, key_text_pairs = None):
.....
for key, text in key_text_pairs:
......
......
x = SomeClass([(1, "abc",), (2, "fff",)])
The value of key_text_pairs inside t开发者_开发知识库he init is None even if I pass a list as in the above statement. Why is it so??
I want to write a generic init which can take all iterator objects...
Thanks
Edit: oops.. I wanted to pass key value pair in the form of tuple... I was just trying to create a toy example.. I am still seeing the same behavior
First of all, when you say for key, text in key_text_pairs
, you are implying that the list has tuples. I tested your code exactly the way it is and that's what happened.
Change x = SomeClass([1, 2, 3])
to x = SomeClass([(1, 1.0), (2, 2.0), (3, 3.0)])
and see if that helps
Cheers
So just looking at that code, is what you posted exactly what you want? Specifically, if you're passing in a list that looks like:
[1, 2, 3]
Then I don't think you want to try to extract it like this:
for key, text in key_text_pairs
You can extract a list of individual integers into a pair of values like key/text.
If I run that code as you posted it, I get a stack trace:
Traceback (most recent call last):
File "test.py", line 6, in <module>
x = SomeClass([1, 2, 3])
File "test.py", line 3, in __init__
for key, text in key_text_pairs:
TypeError: 'int' object is not iterable
You either need to do something like this (extract one value at a time):
class SomeClass(object):
def __init__(self, key_text_pairs = None):
for key in key_text_pairs:
....
x = SomeClass([1, 2, 3])
Or your original list needs to change to be holding pairs of values if you're going to keep that code the same:
x = SomeClass([('a',1),('b',2),('c',3)])
Could you post a traceback?
This is what I get when I run the code:
In [1]: class SomeClass(object):
...: def __init__(self, key_text_pairs = None):
...: for key, text in key_text_pairs:
...: print "key:", key, "text", text
...:
...:
In [2]: x = SomeClass([1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/ryan/<ipython console> in <module>()
/home/ryan/<ipython console> in __init__(self, key_text_pairs)
TypeError: 'int' object is not iterable
In [3]: x = SomeClass(zip('abc', [1,2,3]))
key: a text 1
key: b text 2
key: c text 3
精彩评论