I am working through the O Reilly Python Cookbook and have been struggling with the below code. It is to with calling a method on a parent class using super()
:
class Proxy:
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value) # Call original __setattr__
else:
setattr(self._obj, name, value)
if __name__ == '__main__':
class A:
def __init__(self, x):
self.x = x
def spam(self):
print('A.spam')
a = A(42)
p = Proxy(a)
print(p.x)
print(p.spam())
p.x = 37
print('Should be 37:', p.x)
print('Should be 37:', a.x)
The book states:
In this code the implementation of
__setatrr__()
includes a name check. If the name starts with an underscore it invokes the original implementation of__setattr__()
usingsuper()
. Otherwise, it delegates to the internally held objectself._obj
.
I am confused. How does super()
work then if there is no explicit base class listed?
What exactly then is super()
referring to?