Python: Adding a Method to Both Instances and Classes

Have you ever wondered how to create a method that could be called for both a type object and it's instances? It is unachievable with class/static methods and metaclasses at all. But here is a simple solution. 

import new
class mutualmethod(classmethod): # subclassing classmethod!
  """mutualmethod(function) -> method

  Convert a function to be a mutual method, i. e. a method that can be
  called for both class object and it's instances.

  A mutual method receives the class or it's instance as it's first
  argument.
  """
  def __get__(self, obj, t = None):
    if t is None:
      # I wonder what should I do in this situation.
      # Please leave a comment if you can explain!
      raise NotImplementedError
    if obj is None:
      # creating a method bounded to the type object
      return new.instancemethod(self.__func__, t, type(t))
    else:
      # creating a method bounded to an instance
      return new.instancemethod(self.__func__, obj, t)

And here are some usage examples:

class A(object):
  @mutualmethod
  def myrepr(self):
    if isinstance(self, type):
      pass # you can handle type objects here
    else:
      pass # you can handle type instances here
    return repr(self)

a = A()
a.myrepr() # '<__main__.A object at 0x666666f>'
A.myrepr() # "<class '__main__.A'>"

And a bit more comprehended example:

class HTMLNode(object):
  @mutualmethod
  def pseudo_selector(self, which):
    if isinstance(self, type):
      return '.%s:%s' % (self.__name__, which)
    else:
      return '#%r:%s' % (id(self), which)

class div(HTMLNode):
  pass

my_element = div()
my_element.pseudo_selector('hover') # '#31415926:hover'
div.pseudo_selector('hover')        # '.div:hover'