简体   繁体   English

当类是相同的时,isinstance返回false?

[英]isinstance returning false when class is the same?

def addError(self, e):
    if not isinstance(e, Error):
        raise ValueError('{0} is not type {0}'.format(e, Error))
    self.__errors.append(e)

Message: 信息:

ValueError: <class 'api.utils.Error'> is not type <class 'api.utils.Error'> ValueError: <class 'api.utils.Error'>不是类型<class 'api.utils.Error'>

You're passing the class itself , not an instance of the class. 你正在传递类本身 ,而不是类的实例。 That explains your problem. 这解释了你的问题。

>>> class A:
    pass

>>> isinstance(A, A)
False

What you probably want is to check an instance: 你可能想要的是检查一个实例:

>>> isinstance(A(), A)
True

e is the class api.utils.Error , not an instance of the class. e是类api.utils.Error ,而不是类的实例。 You may want to construct an instance. 您可能想要构造一个实例。

Additionally, your format string has a bug: 此外,您的格式字符串有一个错误:

'{0} is not type {0}'

This ignores the second argument to format and uses the first one for both placeholders. 这忽略了format的第二个参数,并将第一个参数用于两个占位符。 You most likely meant the following: 您最有可能意味着以下内容:

'{0} is not type {1}'

or on Python 2.7, 或者在Python 2.7上,

'{} is not type {}'

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

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