简体   繁体   English

Isinstance()不起作用

[英]Isinstance() doesn't work

For some reason I can't get isinstance() to work on Python 2.7.2 出于某种原因,我无法让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)

And when I compile and run it: 当我编译并运行它时:

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

I get the error message: 我收到错误消息:

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

What am I mising? 我在想什么

You've named your variable list : 您已将变量list命名为:

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

Which is hiding the built-in list . 这隐藏了内置list

Once you've renamed your variable, restart Python (or your IDE). 重命名变量后,重新启动Python(或IDE)。 Since your list is a global variable, it will stick around otherwise. 由于您的list是全局变量,因此它将始终存在。

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. 覆盖诸如list类的python命名类型将变量名与一个新的对象实例绑定在一起。 So later when you tried isinstance with list it failed. 因此,稍后您尝试使用列表进行isinstance失败时。

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. 请注意,如果您污染了名称空间并且正在IDLE中运行,则重新启动IDLE是一个不错的选择。

The problem is you have shadowed the built-in list by assigning to a variable called list : 问题是您通过分配给一个名为list的变量使内置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. 解决方案是为变量使用其他名称。

您将要覆盖list ,尝试print listisinstance诊断这类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM