Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override __type__ method in python object?

Tags:

python

I create a Python class for some mathematical calculations. In that object, I am trying to change type(type) methods result. And my attempts failed.

When I try type() method for my object that appears <class '__main__.MyClassName'> I override type method in my method :

class MyMathOBJ():
.   
.
.
    def __type__(self):
        return "MyMathOBJ"

But when I do that nothing changed. The same result. I was expecting just that result MyMathOBJ.

like image 616
munir.aygun Avatar asked Jan 26 '23 02:01

munir.aygun


1 Answers

You seem to fundamentally misunderstand what type does. type itself is just a class, a metaclass. When you call type on an instance, it returns the class object that corresponds to that instance, pretty much equivalent to instance.__class__. However, you simply want to change the way the class object is represented when you print it, so you'd need to implement a metaclass for MyMathOBJ that overrides __repr__ in the metaclass to accomplish this.

Here is how you accomplish what you are actually trying to do:

In [12]: class PrettyType(type):
    ...:     def __repr__(self):
    ...:         return self.__name__
    ...:

In [13]: class MyMathOBJ(metaclass=PrettyType):
    ...:     pass
    ...:

In [14]: obj = MyMathOBJ()

In [15]: obj
Out[15]: <MyMathOBJ at 0x1060cbcc0>

In [16]: type(obj)
Out[16]: MyMathOBJ
like image 90
juanpa.arrivillaga Avatar answered Jan 28 '23 15:01

juanpa.arrivillaga