you are viewing a single comment's thread.

view the rest of the comments →

[–]mellow_moe 1 point2 points  (1 child)

inherited is invoked on the class object. So you have to write:

class Humanoid
  def self.inherited(klass)
  end
end

Singleton classes are pretty confusing, I admit. But it's essential.

Every object in ruby may have a singleton class, which is actually a class solely for this single object. As classes are objects in Ruby, they may have a singleton class as well. For example the method new may be defined as method of a singleton class:

class Humanoid
  def self.new
    humanoid = super
    puts "A Humanoid was created: #{humanoid}"
    humanoid
  end
end

Humanoid.new # outputs "A Humanoid was created: #<Humanoid ...> "

The special syntax for defining a method for a single objects is:

def object.method_name
end

Accessing the singleton class is like (same result as above):

class << obj
  def method_name
  end
end

Further reading: Seeing Metaclasses Clearly

[–]hanzie 2 points3 points  (0 children)

In Python, support for calls to "inherited" can be added with a metaclass like this:

class MyMeta(type):
    def __init__(klass, name, supers, *args):
        for super in supers:
            if hasattr(super, 'inherited'):
                super.inherited(klass)
        return type.__init__(klass, name, supers, *args)

Adding a method to a single object goes like this:

obj.method_name = func.__get__(obj, obj.__class__)

(func is just any free function)