简体   繁体   English

Python中的枚举:isInstance错误

[英]Enums in Python: isInstance error

What is wrong with this code and is that implementation correct? 此代码有什么问题,该实现正确吗?

from enum import Enum

class Test(object):
    Filters = Enum('Filters', 'A B C')  
    def __init__(self):
        pass

    def aaa(self, filters):
        if(isinstance(filters, self.Filters.B)):
            print 'OK'
        else:
            print 'NOT OK'
if __name__ == '__main__':
    Test().aaa(Test.Filters.B)

Error is: 错误是:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    Test().aaa(Test.Filters.B)
  File "test.py", line 9, in aaa
    if(isinstance(filters, Test.Filters.B)):
TypeError: isinstance() arg 2 must be a type or tuple of types

The error you get is quite clear: 您得到的错误非常清楚:

TypeError: isinstance() arg 2 must be a type or tuple of types

Filters.B is not a class or type. Filters.B不是类或类型。 Instead of using isinstance , just compare the value that you got with the one you want: 无需使用isinstance ,只需将获得的值与所需的值进行比较:

if filters is Test.Filters.B:

Also, Filters is an attribute of the class, not of the instance, so you should probably rather use Test.Filters , although self.Filters seems to work, too. 另外, Filters是类的属性,而不是实例的属性,因此您可能应该使用Test.Filters ,尽管self.Filters似乎也可以。

If you want to know if the filters parameter is a member of the Test.Filters Enum, you have three choices 如果您想知道filters参数是否为Test.Filters枚举的成员,则有三种选择

  • isinstance(filters, Test.Filters)
  • filters in self.Filters

( Test and self are interchangeable.) Testself可以互换。)

If you want to know if the filters parameter is Test.Filters.B then a simple comparison will work: 如果您想知道filters参数是否为Test.Filters.B则可以进行简单的比较:

filters is self.Filters.B
self.Filters.B 

is not defined. 没有定义。 You defined 您定义

Filters.B

Also: 也:

self.Filters.B

needs to be: 需要是:

type(self.Filters.B)

it works like this: 它是这样的:

class A():
    pass

isinstance(3, int) == True
isinstance(3,type(4)) == True
isinstance("hello", type('something')) == True
isinstance("hello", str) == true
isinstance(A(), type(A())) == True
isinstance(A(), A) == True

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

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