23. Doin’ It With Class

Our program needs to manage quite a bit of state. At least:

  • A table sent to us
  • The SAMP connection

Whenever your problems gather state (and that’s quite usual when you handle SAMP messages), think object.

Don’t be scared: An object is essentially like a dictionary with an odd syntax and some keys giving slightly magic functions (“methods”). For instance, a table.load.votable handler:

class VicinitySearcher(object):
  def __init__(self, client):
    self.client = client
    self.cur_table = self.cur_id = None
    self.client.bind_receive_call(
      "table.load.votable", self.load_VOTable)

  def load_VOTable(self, private_key, sender_id, msg_id, mtype,
      params, extra):
    self.cur_table = Table.read(params['url'])
    self.cur_id = params["table-id"]
    self.client.reply(msg_id,
      {"samp.status": "samp.ok", "samp.result": {}})

[See vicinitysearcher.py]

The trivial version of object lore in python is: All functions belonging to an object (methods) have a first argument called self, and whenever you put an attribute on self, you can find it again in other methods’ self, provided these other methods are called on the same instance (i.e., object)..

To call other methods of the same object, use self.methodname.

Create an object (you can now call that an instance and sound a lot cleverer) by calling the class (here: VicinitySearcher(conn)). Whatever you pass into the constructor will be passed to the __init__ method.

Problems

(1)

The action of the SAMP handler is in the make_response_table method; have a look at it. The UCDs used are those of SCS, an ancient standard made before modern UCDs were invented.

Use UCDs to add another column, mag, which, for this exercise, can be just the first column you find with a UCD starting with phot.mag.

Hint: You can iterate over result.table.columns, and you’ll find the UCD in col.meta[’ucd’].

Files


Markus Demleitner, Hendrik Heinl