I was wondering if there was a magic method in Python that supported the type() built-in function, that would allow you to set a custom value to be returned.
Is there a Magic Method for type() in python?
1.4k views Asked by Gilbert Allen At
        	1
        	
        
	
                        
No, there is no such method. An instance's type is not something you can dynamically alter when querying for it, as that would be type-specific behaviour, but you suddenly cannot determine the type that is defining that behaviour!
You can assign a different class to
instance.__class__, but then you'd materially alter the behaviour of that instance, and it is not the instance itself that then changes type whentype()is applied to the instance.Rather than using
type(), use theisinstance()andissubclass()functions instead, and use abstract base types; it is the type object that is then responsible for claiming a specific class or instance as a subclass or instance of the given type, respectively. They can do this via the__issubclass__and__isinstance__hooks.