How can you check if an object is an instance of a class but not any of its subclasses (without knowing the names of the subclasses)? So if I had the below code:
JavaScript
x
22
22
1
def instance_but_not_subclass(object, class):
2
#code
3
return result
4
5
class item(object):
6
7
class item_2(item):
8
9
10
11
class item_n(item):
12
13
a = item()
14
b = item_2()
15
16
c = item_n()
17
18
instance_but_not_subclass(a, item)
19
instance_but_not_subclass(b, item)
20
21
instance_but_not_subclass(c, item)
22
what would go in the #code
space that would produce the output?:
JavaScript
1
5
1
True
2
False
3
4
False
5
Because issubclass()
and isinstance()
always return True
.
Advertisement
Answer
The object.__class__
attribute is a reference to the exact class of an object, so you only need to compare that with your argument
JavaScript
1
3
1
def instance_but_not_subclass(obj, klass):
2
return obj.__class__ is klass
3
Don’t name variables class
, its a keyword and won’t work, use klass
or typ
instead. Also, the variable name object
shadows the build in object
, so use something like obj
.
I personally like the .__class__
variant more, but the more “pythonic” variant would probably be
JavaScript
1
3
1
def instance_but_not_subclass(object, klass):
2
return type(obj) is klass
3
because it doesn’t access any dunder (__
) attributes.