Call this a mini-comparison. Looking back at Python, Ruby and Dart Part 2: Find All Sublclasses, a simpler need sometimes is to query what class an object is an instantiation of.
Ruby
This is quite straightforward in ruby, where all objects descend from Object and Object has Object#class:
1 2 3 4 5 6 7 8 9 10 11 |
|
The above example was run with ruby 2.1.2p95 but I believe the output would be the same going back many versions of ruby.
Python
The example works out almost exactly the same in Python:
1 2 3 4 5 6 7 8 9 10 |
|
You need the extra call to __name__
or else the actual output would be <type 'str'>
but that is just a detail.
One thing I will note, is that at least in python 2.7.9 that I am trying this on, using type(x).__name__
instead didn’t return the results that some posts online seem to indicate it would. Maybe I am missing something here?
1 2 3 4 5 6 7 8 9 10 |
|
That output would make it seem that object3’s type is a general type of instance, and not a type of MyClass
.
Dart
Dart somewhat recently added the Object#runtimeType property, which makes this example very similar to the two above:
1 2 3 4 5 6 7 8 9 10 11 |
|
I am running that in dart 1.9.1.
How Useful is This?
So the three examples above come out very comparable and overall very easy to access. I would say that outputting the string name of the class an object is instantiated from is most useful in logging and debugging. What you care about at runtime more often is how does an object behave - does it implement a need interface. In all three languages, that is not as straightforward as detecting the class, because many different objects built from many different classes may implement the same interface.
So next time I will take a look at how to detect if an object implements the interface you need.