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:
def instance_but_not_subclass(object, class):
#code
return result
class item(object):
class item_2(item):
...
class item_n(item):
a = item()
b = item_2()
...
c = item_n()
instance_but_not_subclass(a, item)
instance_but_not_subclass(b, item)
...
instance_but_not_subclass(c, item)
what would go in the #code
space that would produce the output?:
True
False
...
False
Because issubclass()
and isinstance()
always return True
.
The
object.__class__
attribute is a reference to the exact class of an object, so you only need to compare that with your argumentDon't name variables
class
, its a keyword and won't work, useklass
ortyp
instead. Also, the variable nameobject
shadows the build inobject
, so use something likeobj
.I personally like the
.__class__
variant more, but the more "pythonic" variant would probably bebecause it doesn't access any dunder (
__
) attributes.