Discreet Cosine Transform

A few thoughts on ruby, video and other things

Python, Ruby and Dart Part 2.1: Find the Class of an Object

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
object1 = 1
object2 = 'test'

class MyClass
end

object3 = MyClass.new

puts object1.class #prints Fixnum
puts object2.class #prints String
puts object3.class #prints MyClass

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
object1 = "test"
object2 = 1
class MyClass:
  pass

object3 = MyClass()

print object1.__class__.__name__ #prints "str"
print object2.__class__.__name__ #prints "int"
print object3.__class__.__name__ #prints "MyClass"

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
object1 = "test"
object2 = 1
class MyClass:
  pass

object3 = MyClass()

print type(object1).__name__ #prints "str"
print type(object2).__name__ #prints "int"
print type(object3).__name__ #prints "instance"

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
class MyClass {}

void main() {
  var object1 = 1;
  var object2 = "test";
  var object3 = new MyClass();

  print(object1.runtimeType); //prints "int"
  print(object2.runtimeType); //prints "String"
  print(object3.runtimeType); //prints "MyClass"
}

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.

Comments