I'm making a game in Python and I want to check if two instantiated objects have the same superclass. For example if I have a class superclass1
and two subclasses of that superclass called sub1
and sub2
, I want to see if an instance of sub1
and an instance of sub2
are both instances of superclass1
. Is there a command for this?
Asked
Active
Viewed 41 times
-1
-
1list intersection using the instance's class `__base__` (or `__mro__` )? (e.g. something like https://stackoverflow.com/questions/1401661/list-all-base-classes-in-a-hierarchy-of-given-class should probably give you enough information to do what you need) – Mike 'Pomax' Kamermans Jun 26 '23 at 16:59
-
2EVERY pair of objects in Python share a superclass - `object`, if nothing else. – jasonharper Jun 26 '23 at 17:01
1 Answers
3
You can use the isinstance
function for this
class Parent():
def __init__(self):
...
class ChildA(Parent):
def __init__(self):
...
class ChildB(Parent):
def __init__(self):
...
# instantiate the child class
child_a = ChildA()
# check if that child class is an instance of the parent class
print(isinstance(child_a, Parent))
# => True

JRiggles
- 4,847
- 1
- 12
- 27
-
-
Glad I could help. If this answer works for you, please mark it as 'Accepted' so that others know this question has been answered – JRiggles Jun 26 '23 at 17:09