Testing an object is a subclass of the type of another instance.

I have this code:

class Item:
    def __init__(self,a):
        self.a=a

class Sub(Item):
    def __init__(self,a,b):
        self.b=b
        Item.__init__(self,a)

class SubSub(Sub):
    def __init__(self,a,b,c):
       self.c=c
       Sub.__init__(self,a,b)

obj1=Item(1)
obj2=Sub(1,2)
obj3=SubSub(1,2,3)

Now I want to check whether obj2, and obj3instances of classes that are subclasses obj1, as well as a subclass Item.

That's what I understand, I know what I can use isinstance()to find if obj2there is one Sub. and I know what I can use issubclass(Sub, Item). But let me say that I did not know what class obj2was.

I tried using issubclass(type(obj2),Item), but this does not work, because it type()returns a separate object, which I really do not understand. And this is only one problem, although I believe that the answer to this question will help me solve some other problems that I have.

, __class__, , .

+4
1

obj type():

isinstance(obj2, type(obj1))

, , . type() , .

issubclass() :

issubclass(type(obj2), Item)

:

>>> class Item:
...     def __init__(self,a):
...         self.a=a
... 
>>> class Sub(Item):
...     def __init__(self,a,b):
...         self.b=b
...         Item.__init__(self,a)
... 
>>> class SubSub(Sub):
...     def __init__(self,a,b,c):
...        self.c=c
...        Sub.__init__(self,a,b)
... 
>>> obj1=Item(1)
>>> obj2=Sub(1,2)
>>> obj3=SubSub(1,2,3)
>>> isinstance(obj2, type(obj1))
True
>>> issubclass(type(obj2), Item)
True

, , , . type(obj2) , , , , , .

, ; , , :

>>> type(obj1) is Item
True
>>> type(obj2) is Sub
True
>>> type(obj3) is SubSub
True
+4

All Articles