Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1625
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

相关标签:
15条回答
  • 2020-12-08 08:35

    JavaScript has noSuchMethod, but unfortunately this is only supported by Firefox/Spidermonkey.

    Here is an example:

    wittyProjectName.__noSuchMethod__ = function __noSuchMethod__ (id, args) {
       if (id == 'errorize') {
        wittyProjectName.log("wittyProjectName.errorize has been deprecated.\n" +
                             "Use wittyProjectName.log(message, " +
                             "wittyProjectName.LOGTYPE_ERROR) instead.",
                             this.LOGTYPE_LOG);
        // just act as a wrapper for the newer log method
        args.push(this.LOGTYPE_ERROR);
        this.log.apply(this, args);
      }
    }
    
    0 讨论(0)
  • 2020-12-08 08:37

    Some use cases of method_missing can be implemented in Python using __getattr__ e.g.

    class Roman(object):
      def roman_to_int(self, roman):
        # implementation here
    
      def __getattr__(self, name):
        return self.roman_to_int(name)
    

    Then you can do:

    >>> r = Roman()
    >>> r.iv
    4
    
    0 讨论(0)
  • 2020-12-08 08:45

    PHP objects can be overloaded with the __call special method.

    For example:

    <?php
    class MethodTest {
        public function __call($name, $arguments) {
            // Note: value of $name is case sensitive.
            echo "Calling object method '$name' "
                 . implode(', ', $arguments). "\n";
        }
    }
    
    $obj = new MethodTest;
    $obj->runTest('in object context');
    ?>
    
    0 讨论(0)
  • 2020-12-08 08:45

    C# now has TryInvokeMember, for dynamic objects (inheriting from DynamicObject)

    0 讨论(0)
  • 2020-12-08 08:49

    Perl has AUTOLOAD which works on subroutines & class/object methods.

    Subroutine example:

    use 5.012;
    use warnings;
    
    sub AUTOLOAD {
        my $sub_missing = our $AUTOLOAD;
        $sub_missing =~ s/.*:://;
        uc $sub_missing;
    }
    
    say foo();   # => FOO
    

    Class/Object method call example:

    use 5.012;
    use warnings;
    
    {
        package Shout;
    
        sub new { bless {}, shift }
    
        sub AUTOLOAD {
            my $method_missing = our $AUTOLOAD;
            $method_missing =~ s/.*:://;
            uc $method_missing;
        }
    }
    
    say Shout->bar;         # => BAR
    
    my $shout = Shout->new;
    say $shout->baz;        # => BAZ
    
    0 讨论(0)
  • 2020-12-08 08:50

    Objective-C supports the same thing and calls it forwarding.

    0 讨论(0)
提交回复
热议问题