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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With