class a:
pass
class b(a):
pass
c = b()
type(c) == a #returns False
Is there an alternative to type()
that can check if an object inherits from a class?
是的, isinstance : isinstance(obj, Klass)
isinstance
and issubclass
are applicable if you know what to check against. If you don't know, and if you actually want to list the base types, there exist the special attributes __bases__
and __mro__
to list them:
To list the immediate base classes, consider class.__bases__
. For example:
>>> from pathlib import Path
>>> Path.__bases__
(<class 'pathlib.PurePath'>,)
To effectively recursively list all base classes, consider class.__mro__
or class.mro()
:
>>> from pathlib import Path
>>> Path.__mro__
(<class 'pathlib.Path'>, <class 'pathlib.PurePath'>, <class 'object'>)
>>> Path.mro()
[<class 'pathlib.Path'>, <class 'pathlib.PurePath'>, <class 'object'>]
>>> class a:
... pass
...
>>> class b(a):
... pass
...
>>> c = b()
>>> d = a()
>>> type(c) == type(d)
True
type()
returns a type object. a is the actual class, not the 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.