0

何らかの理由で isinstance() を Python 2.7.2 で動作させることができません

def print_lol(the_list, indent=False, level=0):
    for item in the_list:
        if isinstance(item, list):
            print_lol(item, indent, level+1)
        else:
            print(item)

そして、コンパイルして実行すると:

>>> list = ["q", "w", ["D", ["E", "I"]]]
>>> print_lol(list)

エラーメッセージが表示されます:

if isinstance(item, list):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

私は何が欠けていますか?

4

4 に答える 4

8

You've named your variable list:

>>> list = ["q", "w", ["D", ["E", "I"]]]

Which is hiding the built-in list.

Once you've renamed your variable, restart Python (or your IDE). Since your list is a global variable, it will stick around otherwise.

于 2012-04-14T06:09:04.530 に答える
2

This is where you have issue

>>> list = ["q", "w", ["D", ["E", "I"]]]

overwriting python named types like list binds the variable name with a new object instance. So later when you tried isinstance with list it failed.

When ever you create new variable, please refrain from naming it differently from built-in and not to conflict with the namespace.

In this example using the following would work like a breeze

>>> mylist = [w for w in mylist if len(w) >= 3 and diff(w)]
>>> isinstance(mylist,list)
True

Please note, if you have polluted the namespace and you are running in IDLE, restarting IDLE is a good alternative.

于 2012-04-14T06:09:18.847 に答える
1

The problem is you have shadowed the built-in list by assigning to a variable called list:

list = ["q", "w", ["D", ["E", "I"]]]

You should try to avoid using any of the built-in names for variables, because this will often result in confusing errors. The solution is to use a different name for your variable.

于 2012-04-14T06:09:10.727 に答える
1

You are overwriting list, try print list before isinstance to diagnose this sort of problem.

于 2012-04-14T06:10:07.307 に答える