简体   繁体   中英

Python-How do I find if a variable is a particular class?

I'm writing a script in python3. I have a variable named r my code is like this:

if type(r) == 'twx.botapi.botapi.Error':
     print('Error!')
else:
     print('success!')

When i use type(r) i get this:

<class 'twx.botapi.botapi.Error'>
or
<class 'twx.botapi.botapi.Message'>

I tried using these too but i got no answer:

if type(r) == <class 'twx.botapi.botapi.Error'>:
     print('Error!')
else:
     print('success!')

How can I find if the class type is a kind of error or message ?

Depending on whether the variable points to an instance of a class or the class object itself you can use isinstance or issubclass , eg

from twx.botapi.botapi import Error, Message

if issubclass(r, Error):
    print('Error!')
else:
    print('success!')

Both functions accept a tuple of objects for the second parameter.

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