Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance() method returns false answer in Python 3

Look at the following code:

a = 3
type(a) == object
False
isinstance(a, object)
True

How is this to be explained?

like image 955
user8270077 Avatar asked Sep 04 '25 16:09

user8270077


2 Answers

Everything is an object in Python, which includes ints, strings, functions and classes. Therefore, isinstance(a, object) will return you True . But 3 is actually an integer, which is a sub_class create from object. Therefore type(a) can equal to int only.

I can give you an example.

Suppose we have two classes, Sub is a sub_class of Base.

class Base:
    def __init__(self):
        self.kappa='kappa'
class Sub(Base):
    def __init__(self):
        super().__init__()

obj=Base()
int_rino=Sub()


print(isinstance(obj, Base))
print(isinstance(obj, Sub))
print(isinstance(int_rino, Base))
print(isinstance(int_rino, Sub))


print(type(int_rino) == Base)

The result will be:

True
False
True
True
False
like image 121
Marcus.Aurelianus Avatar answered Sep 07 '25 18:09

Marcus.Aurelianus


This is a common construct in most object-oriented languages that support inheritance. When a child class (in your case int) inherits from a parent (in your case object), it is said to have an "is-a" relationship. That is, an int is a (or an) object.

This "is-a" relationship is what isinstance is checking. From the docs:

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

There is a similar issubclass function to check the same relationship for a class instead of an instance of that class. In fact, in most cases, isinstance(x, y) == issubclass(type(x), y).

type returns the exact class that an object was constructed from. That means that checking type(3) == object is exactly equivalent to checking int == object. Hopefully you can see that that's unambiguously false.

On a related tangent, classes should always be the same reference within a given run of the interpreter, so you can use is instead of == for comparison. So type(3) is int will be true. That's how == is implemented for all the types you're ever likely to come across anyway.

like image 40
Mad Physicist Avatar answered Sep 07 '25 17:09

Mad Physicist