precedence of [] vs .

Michael Tobis mtobis at gmail.com
Thu Aug 14 18:46:28 EDT 2008


I wrote some code to test the precedence of getitem vs getattr; it
shows that getitem binds tighter.

I have been handed some code that relies on the observed behavior.
However, the Nutshell precedence list claims the opposite. Is the
Nutshell wrong or am I missing something or is this a bug?

class a(object):
    def __getitem__(self,item):
	return str(item)[:-1]

class b(object):
    def __getattr__(self,item):
	return str(item)[::-1]

Albert = a()
print Albert['abcd']
# prints 'abc'

Barney = b()
print Barney.abc
# print 'cba'

print Barney.Albert['abcd']
# raises TypeError; tries to evaluate 'treblA'['abcd']
# I expected 'cba' based on Nutshell 2d Ed p 50



More information about the Python-list mailing list