3

Possible Duplicate:
Dynamic Finders and Method Missing in Python

I know you can do this in Ruby, but how would it be done in Python?

So basically you could maybe to a regex on the method call that didn't exist, and create 'syntactic sugar'.

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

2

Define __getattr__.

But that still won't make s./.*/ valid syntax, if that's what you have in mind. Python's syntax is nowhere as bendable as Ruby's.

1

You can override __getattribute__ on an object to handle requests for attributes that do not exist. This only works for new-style classes. If you have old-style classes, you can use delnans answer.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 1
    Terminology nitpicking: There is no overloading (as in http://en.wikipedia.org/wiki/Method_overloading) in Python or in Ruby. Only overriding. –  Nov 10 '10 at 15:11
  • 2
    `__getattribute__` is called on *all* attribute lookups. delnan's answer is correct for both new and old-style classes. – Glenn Maynard Nov 10 '10 at 15:27
  • You confused me :) I thought that (correctly, as @Glenn suggests and the docs confirm) that `__getattr__` is called for missing attributes/methods (as the question asks) while `__getattribute__` is used *always* when defined. –  Nov 10 '10 at 15:30