Hello aficionados,
I am chugging along and currently on the topic of Attribute Fetch for Built-ins Skips Instances
of my Pythonic studies.
I am testing the following test script:
class C: # New-style: 3.X and 2.X
data = 'spam'
def __init__(self, one, two):
self.one = one
self.two = two
# Test 1: Comment out --- Test 2: Uncomment out
def __getattribute__(self, item):
print('item = ', item)
return '<getattribute>: ' + item
def __getitem__(self, i): # Redefine built-ins
print('<getitem>: ' + str(i))
return self.data[i] # Run expr or getattr
X = C(33, 55) # Create instance of object
print(X[1]) # __getitem__ called for index operation
# Returned for __getattribute__ intercept call
# <getattribute>: data
From the print statement, you can see that we are performing an indexing operation. The index operation causes the __getitem__
overloading intercept method to be automatically called. There are two test cases here.
__getattribute__
intercept method is commented out__getattribute__
intercept method is not commented out.
Test observations in order of tests enumerated above:
-
The index passed in is
1
(one). The__getitem__
overloading method is called due to the indexing operation. It has the return expressionself.data[i]
. This calls the class attributedata
to be called. The letter returned is a function of the indexi
, passed in. So far so good. -
This one is a bit trickier. The reason being is that
`data` = ' <getattribute>: ' + item.
Or, data
= item
according to the print statement.
But data[i]
equals the string character of the following total string:
'<getattribute>: data'.
You can change the value of the index passed in, in the print statement to verify.
Can someone please offer an explanation to help in my understanding as to why item
equals data
and data[i]
equals a string element of (depending on the index passed in):
<getattribute>: data