We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Infinite Method Object

Number: 2772

Difficulty: Easy

Paid? Yes

Companies: N/A


Problem Description

Design a function that returns an object supporting an "infinite-method" interface. In other words, no matter what property (method name) is called on the object (followed by parentheses), it should always return that method’s name as a string. For example, calling obj.abc123() must return "abc123".


Key Insights

  • The object must dynamically handle any method call.
  • Dynamic languages like Python and JavaScript allow interception of attribute/method access, making this task straightforward.
  • In statically typed languages (C++/Java), we simulate the behavior using techniques like operator overloading (in C++) or a dynamic proxy (in Java).
  • The core trick is to intercept the method access, then return a callable that when executed returns the name of the method.

Space and Time Complexity

Time Complexity: O(1) per method call. Space Complexity: O(1) per method call.


Solution

We create an object (or use a factory function) that returns an "infinite-method" object. In Python, override getattr to capture any method name and return a lambda returning that name. In JavaScript, use a Proxy to intercept any property access and return a function that returns the property name. In C++, since dynamic member functions aren’t directly supported, we overload the operator[] so that accessing a key provides a callable lambda which returns that key. In Java, we use a dynamic proxy that intercepts all method calls on an interface and returns the invoked method's name. Each solution capitalizes on language-specific features to handle calls to methods that are not explicitly defined.


Code Solutions

# Python solution using __getattr__ to intercept any method call.
class InfiniteMethodObject:
    # When an attribute access occurs, return a lambda that returns the attribute name.
    def __getattr__(self, name):
        return lambda *args, **kwargs: name

def createInfiniteObject():
    return InfiniteMethodObject()

# Example usage:
if __name__ == "__main__":
    obj = createInfiniteObject()
    print(obj.abc123())  # prints "abc123"
← Back to All Questions