Search code examples
pythonbuilt-in

Is it possible to change type function behavior?


We can change behavior of str(object) function by defining __str__ in object class. Is it possible to do so with type function? I'm just curious, none use case.

Try with __class__ doesn't work:

class A:
    def __class__(self):
        print(1)
        return "x"

obj = A()
print(type(obj))

it doesn't print 1 or do anything with x. It just prints <class '__main__.A'> as usual.


Solution

  • You can do this with a metaclass:

    
    class Meta(type):
        def __repr__(cls):
            return "Fire"
    
    class A(metaclass=Meta):
        pass
    
    print(type(A()))
    # Prints "Fire"