| 1 | class Fluent: |
| 2 | def __init__(self, cache=None): |
| 3 | self._cache = cache or [] |
| 4 | |
| 5 | # Build the cache, and handle special cases |
| 6 | def _(self, name): |
| 7 | # Enables method chaining |
| 8 | return Fluent(self._cache + [name]) |
| 9 | |
| 10 | # Reflection |
| 11 | def __getattr__(self, name): |
| 12 | return self._(name) |
| 13 | |
| 14 | # Set name |
| 15 | def _name(self, name): |
| 16 | return self._(name) |
| 17 | |
| 18 | # Final method call |
| 19 | def execute(self): |
| 20 | return " ".join(self._cache) |
| 21 | |
| 22 | # New object |
| 23 | fluent = Fluent() |
| 24 | |
| 25 | # 'is' is a Python reserved word |
| 26 | result = fluent.hello.my.name._('is')._name('Adierebel').execute() |
| 27 | print(result) |
| 28 | |
| 29 | # API example |
| 30 | api = fluent.get.user.info.execute() |
| 31 | print(api) |
| 1 | class Example(object): |
| 2 | def foo(self): |
| 3 | print("this is foo") |
| 4 | def bar(self): |
| 5 | print("this is bar") |
| 6 | def __getattr__(self, name): |
| 7 | def method(*args): |
| 8 | print("tried to handle unknown method " + name) |
| 9 | if args: |
| 10 | print("it had arguments: " + str(args)) |
| 11 | return method |
| 12 | |
| 13 | example = Example() |
| 14 | |
| 15 | example.foo() # prints "this is foo" |
| 16 | example.bar() # prints "this is bar" |
| 17 | example.grill() # prints "tried to handle unknown method grill" |
| 18 | example.ding("dong") # prints "tried to handle unknown method ding" |
| 19 | # prints "it had arguments: ('dong',)" |
To add a comment, please login or register first.
Register or Login