简体   繁体   中英

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'>

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. 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. You most likely meant the following:

'{0} is not type {1}'

or on Python 2.7,

'{} is not type {}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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