Saturday, 21 April 2018

What is the difference between a 'Type' and an 'Object' in Python

Here is a simple exploration of the two functions. I found it illuminating going through this exercise. I often will create a simple program exploring the ins and outs of simple functions and save them for reference:



#
# Testing isinstance and issubclass

#

class C1(object):
def __init__(self):
object.__init__(self)

class B1(object):
def __init__(self):
object.__init__(self)


class B2(B1):
def __init__(self):
B1.__init__(self)

class CB1(C1,B1):
def __init__(self):
# not sure about this for multiple inheritance
C1.__init__(self)
B1.__init__(self)


c1 = C1()
b1 = B1()
cb1 = CB1()

def checkInstanceType(c, t):
if isinstance(c, t):
print c, "is of type", t
else:
print c, "is NOT of type", t


def checkSubclassType(c, t):
if issubclass(c, t):
print c, "is a subclass of type", t
else:
print c, "is NOT a subclass of type", t

print "comparing isinstance and issubclass"
print ""

# checking isinstance

print "checking isinstance"

# can check instance against type
checkInstanceType(c1, C1)
checkInstanceType(c1, B1)
checkInstanceType(c1, object)

# can check type against type
checkInstanceType(C1, object)
checkInstanceType(B1, object)


# cannot check instance against instance
try:
checkInstanceType(c1, b1)
except Exception, e:
print "failed to check instance against instance", e

print ""

# checking issubclass

print "checking issubclass"

# cannot check instance against type
try:
checkSubclassType(c1, C1)
except Exception, e:
print "failed to check instance against type", e

# can check type against type
checkSubclassType(C1, C1)

checkSubclassType(B1, C1)
checkSubclassType(CB1, C1)
checkSubclassType(CB1, B1)

# cannot check type against instance
try:
checkSubclassType(C1, c1)
except Exception, e:
print "failed to check type against instance", e



Edit:
Also consider the following as isinstance can break API implementations. An example would be an object that acts like a dictionary, but is not derived from dict. isinstance might check that an object is a dictionary, even though the object supports dictionary style access:
isinstance considered harmful



Edit2:




Can someone please give me an example of a distinction between passing a Type as a second argument versus passing an Object?





After testing the above code it tells me the second parameter must be a type. So in the following case:



checkInstanceType(c1, b1)


The call will fail. It could be written:



checkInstanceType(c1, type(b1))



So if you want to check the type of one instance against another instance you have to use the type() builtin call.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...