newstyle classes and __getattribute__

Stefan Sonnenberg-Carstens stefan.sonnenberg at freenet.de
Fri Oct 28 17:52:55 EDT 2005


James Stroud schrieb:
> On Friday 28 October 2005 14:26, Stefan Sonnenberg-Carstens wrote:
> 
>>Hi there,
> 
> [..clip..]
> 
>>Now, I do this:
>>
>>class T(object):
>>	def __init__(self,name='',port=80):
>>		self.name=name
>>		self.port=port
>>	def __getattribute__(self,key):
>>		if key=='somekey':
>>			return None
> 
> [..snip..]
> 
>>But, then surprise:
>> >>> t = T(name="test123",port=443)
>> >>> dir(t)
>>
>>[]
>>
>>What the hell is going wrong here ?
> 
> 
> __getattribute__ is returning None in all cases and dir() is converting None 
> to [].
> 
> Anyway, you should have done this:
> 
> py> class T(object):
> ....     def __init__(self,name='',port=80):
> ....             self.name=name
> ....     def __getattribute__(self,key):
> ....             if key=='somekey':
> ....                     return None
> ....             else:
> ....               return object.__getattribute__(self, key)
> ....
> py> t = T(name="test123",port=443)
> py> dir(t)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
> '__hash__', '__init__', '__module__', '__new__', '__reduce__', 
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'name']
> 
> James
> 
Sorry, but I am right that you explicitly call a "super" 
__getattribute__ on object and pass it a reference to self and the
desired key ?
Only asking for clarification ...

But why does that work under 2.4.1, and even under ActiveState's 2.4.1 ?
Was that changed between those 2 releases ?
Intuitive behaviour of __getattribute__ would be:
If a key is not handeld in that function, return what you already got.

Cheers,
Stefan




More information about the Python-list mailing list