I define a NE_Conv2d class and override its __getattr__. When I try to get an existing attribute from one instance of this class, __getattr__ is called and enter infinite recursion.
I know one need to deal with __getattr__ carefully to avoid infinite recursion, but apparently the conv attribute already exists after __init__ is called. So when I try to get conv attribute, __getattr__ should not be called.
from torch import nn
class NE_Conv2d(nn.Module):
'''Nonexpansive conv2d'''
def __init__(self, *k, **kw):
super(NE_Conv2d, self).__init__()
self.conv = nn.Conv2d(*k, **kw)
print('foo')
def __getattr__(self, attr):
return getattr(self.conv, attr)
a = NE_Conv2d(3, 32, 5)
print(a)
print(a.conv)
Above code should print info about a and a.conv, but enter infinite recursion when trying to get a.conv.
__getattr__is only called if an attribute (convhere) is not found on an object. In this caseself.convis assigned in the__init__method so__getattr__will not be called ifa.convis accessed.RecursionError: maximum recursion depth exceedederror.