See if type meta object is an instance of another class
Question:
I’m wondering if there’s a way of seeing whether a class is inherited from another class based on the type
object for a given object.
Say I have the class MyList
as defined below:
class MyList(list):
pass
Now consider the following:
>>> my_list = MyList()
>>> type(my_list).__name__
'MyList'
>>> isinstance(my_list, list)
True # as expected
>>> isinstance(type(my_list), list)
False # how can I get this to be True?
So my questions are:
- What is a pythonic way of seeing whether the type object for a class is an instance of (inherited from) another class?
- Can you retrieve the class of an object based on the
type
metaclass instance for it? I would imagine this as something like type(my_list).class
Answers:
Purely as a pro-forma action …
The solution is to use issubclass()
:
>>> class MyList(list):
... pass
...
>>> my_list = MyList()
>>> issubclass(MyList, list)
True
>>> issubclass(my_list.__class__, list)
True
I’m wondering if there’s a way of seeing whether a class is inherited from another class based on the type
object for a given object.
Say I have the class MyList
as defined below:
class MyList(list):
pass
Now consider the following:
>>> my_list = MyList()
>>> type(my_list).__name__
'MyList'
>>> isinstance(my_list, list)
True # as expected
>>> isinstance(type(my_list), list)
False # how can I get this to be True?
So my questions are:
- What is a pythonic way of seeing whether the type object for a class is an instance of (inherited from) another class?
- Can you retrieve the class of an object based on the
type
metaclass instance for it? I would imagine this as something liketype(my_list).class
Purely as a pro-forma action …
The solution is to use issubclass()
:
>>> class MyList(list):
... pass
...
>>> my_list = MyList()
>>> issubclass(MyList, list)
True
>>> issubclass(my_list.__class__, list)
True