tags:

views:

151

answers:

3

Trying to understand when to use which. The documentation mentions __ getattribute__ applies to new-style classes- What are new-style classes?

+1  A: 

New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__ class method in addition to __init__ and have somewhat more rational low-level behavior.

Usually, you'll want to override __getattr__ (if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.

Extra info: http://www.devx.com/opensource/Article/31482/0/page/4

Mr Fooz
+2  A: 

New style classes inherit from object:

class SomeObject(object):
    pass

old style classes don't:

class SomeObject:
    pass

See http://docs.python.org/tutorial/classes.html, http://wiki.python.org/moin/NewClassVsClassicClass, http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python for details.

sdolan
+7  A: 

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

You almost certainly want __getattr__.

Ned Batchelder