Super python class

Since type is the superclass of all classes, why isinstance(1,type) gives as False ? I misunderstand the concept?

+6
source share
2 answers

type not a superclass of all classes. This is the type of all classes (which do not have a custom metaclass). Note the difference:

 >>> isinstance(1, int) True >>> isinstance(1, type) False >>> isinstance(int, type) True 

The number 1 is not an instance of a type. Rather, the int type itself is an instance of type .

Edit:

These examples may help you:

 >>> isinstance(1, int) True >>> issubclass(1, int) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> issubclass(1, int) TypeError: issubclass() arg 1 must be a class >>> class Foo(object): ... pass >>> isinstance(Foo, type) True >>> issubclass(Foo, type) False # Note the difference from the previous! >>> isinstance(Foo, object) True >>> issubclass(Foo, object) True >>> isinstance(int, type) True >>> issubclass(int, type) False # Note the difference from the previous! 

From your comment, it seems you don't understand how inheritance works. There is a difference between an instance of a type and a subclass (or subtype) of a type. If an object X is an instance of type A, and type A is a subclass of type B, then X is also an instance of B. But if type A is an instance of type B, then X is not an instance of B. In other words, subclasses are transitive, but the instances are not.

An analogy of the real world would be between something like “species” and “homo sapiens”. We can say that “view” is a type, and “homo sapiens” is an instance of this type; in other words, "homo sapiens" is a special kind. But "homo sapiens" is also a type, and an individual person is an instance of this type. For example, Barack Obama (to choose a famous example) is an example of "homo sapiens"; that is, he is a special homo sapiens. But Barack Obama is not an example of species; he is not the species itself.

The relationships between type , int and number 1 are similar. The number 1 is an instance of int , and int is an instance of type , but this does not mean that 1 is an instance of a type.

+11
source

This is because type not a supertype of all built-in types. object is.

+4
source

Source: https://habr.com/ru/post/923745/


All Articles