I came across this piece of code, and I am surprised that it adds an element to the list.
Here's the code:
class Wrapper:
def __init__(self, object):
self.wrapped = object
def __getattr__(self,attrname):
print('Trace: '+attrname)
return getattr(self.wrapped,attrname)
X = Wrapper([1,2,3])
X.append(4)
print(X.wrapped)
I am surprised because if I run type(X), I get __main__.Wrapper, which makes sense because X is an object of class Wrapper. Hence, I am unsure why X.append adds to the list in the attribute wrapped directly. After all, the type of X isn't list but Wrapper.
Shouldn't the call have been X.wrapped.append(4)? This works as well.
I am a beginner, and this might be a basic question. I'd appreciate any thoughts, and thanks for any help.
This code was adopted from Mark Lutz's book. I am using Anaconda 3.6 distribution
X.__getattr__('append')(4).Objectis a built-in name. Don't use it as your variable names. Secondly, It's becauseself.wrappedis a list and__getattr__is calling thelist'sappendmethod.