What exactly does the last line of IClass do??
subclasscheck overloads subclasscheck but, normally while
overloading an operator we do something like:
adt + 4.0
here, adt is the user defined type = user class object(instance) and 4.0
is a builtin type which has say .real, .imaginary pre-configured so if
adt is complex then this becomes:
adt.(self, other)
add(self, other)
so a reference to ‘adt’ is generated and fed to ‘self’ and ‘other’ refers
to 4.0
But in the example below:
class IClass(object):
def __init__(self):
self.implementors = set()
def register(self,C):
self.implementors.add(C)
def __instancecheck__(self,x):
return self.__subclasscheck__(type(x))
def __subclasscheck__(self,sub):
return any(c in self.implementors for c in sub.mro())
# Now, use the above object
IFoo = IClass()
IFoo.register(Foo)
IFoo.register(FooProxy)
f = Foo() # Create a Foo
g = FooProxy(f) # Create a FooProxy
isinstance(f, IFoo) # Returns True
isinstance(g, IFoo) # Returns True
issubclass(FooProxy, IFoo) # Returns True
Here what are self and sub for subclasscheck?? How is
subclasscheck being overloaded??
Anyway, assuming it is being overloaded somehow.. a reference to FooProxy is
passed to self and IFoo->sub. So.. IFoo.mro() would generate the method
resolution order for instance IFoo and therefore for IClass.. which
would be just object.. umm.. wth??
Could somone explain what is going on here?? Basically ‘any’ should return
True if FooProxy is a sub-class of the grouped-classes in IClass.
__subclasscheck__is the method to override built-inissubclass.The call
issubclass(X,Y)first checks whetherY.__subclasscheck__exists, and if so, callsY.__subclasscheck__(X)instead of its normal implementation.similarly;
__instancecheck__is the method to override built-inisinstance. The callisinstance(X, Y)first checks whetherY.__instancecheck__exists, and if so, callsY.__instancecheck__(X)instead of its normal implementation.
lets consider above example;create new class
FooProxy3; and checkissubclassfor that; and it will returnFalse(as perOut[122]) because we are looking for subclass check inIFoo.implementors; and there it is not present (as perIn[123])but when we have
registerFooProxy(here it means; now we can see itIFoo.implementors); we can see itFoxproxy3inIFoo.implementors(as perIn[126])so when we check
issubclass; it wil returnTrue.for more info;
Customizing instance and subclass checks
Overloading isinstance() and issubclass()