Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance is an "object", but class is not a subclass of "object": how is this possible?

How is it possible to have an instance of a class which is an object, without the class being a subclass of object? here is an example:

>>> class OldStyle(): pass
>>> issubclass(OldStyle, object)
False
>>> old_style = OldStyle()
>>> isinstance(old_style, object)
True
like image 540
Eric O Lebigot Avatar asked Mar 14 '12 09:03

Eric O Lebigot


People also ask

Can an object be a subclass of another class?

Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.

Is class is an instance of subclass?

You can make a class (called a subclass , derived class, or child class) a specialization of another class (called a superclass , base class, or parent class). A subclass inherits the methods and instance data of its superclasses, and is related to its superclasses by an is-a relationship.

Is there a way to check if a class is a subclass of another class?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

How do you determine if a certain class is a subclass of another class Java?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.


1 Answers

In Python 2, type and class are not the same thing, specifically, for old-style classes, type(obj) is not the same object as obj.__class__. So it is possible because instances of old-style classes are actually of a different type (instance) than their class:

>>> class A(): pass
>>> class B(A): pass
>>> b = B()

>>> assert b.__class__ is B
>>> issubclass(b.__class__, A) # same as issubclass(B, A)
True
>>> issubclass(type(b), A)
False

>>> type(b)
<type 'instance'>
>>> b.__class__
<class __main__.B at 0x10043aa10>

This is resolved in new-style classes:

>>> class NA(object): pass
>>> class NB(NA): pass
>>> nb = NB()
>>> issubclass(type(nb), NA)
True
>>> type(nb)
<class '__main__.NB'>
>>> nb.__class__
<class '__main__.NB'>

Old-style class is not a type, new-style class is:

>>> isinstance(A, type)
False
>>> isinstance(NA, type)
True

Old style classes are declared deprecated. In Python 3, there are only new-style classes; class A() is equivalent to class A(object) and your code will yield True in both checks.

Take a look at this question for some more discussion: What is the difference between old style and new style classes in Python?

like image 59
hamstergene Avatar answered Oct 29 '22 00:10

hamstergene