一晚上遇到两常见的小错误,分享一下!
AttributeError: ‘xxx’ object has no attribute ‘xxx’
明明已经定义了,代码仍然出错!!!
原因1:int()双下划线的忽略(当__使用双下划线时会变为紫色为正确)
原因2:路径中有中文。
TypeError: xxx takes 2 positional arguments but 3 were given
原因:传参问题。注意:self表示创建的类实例本身,所以在内部就可以把各种属性绑定到self。在创建实例的时候,就不能传入空的参数,必须传入与方法匹配的参数。但注意self不需要传,Python解释器会自己把实例变量传进去。
错误演示:
class ABC:
...
def channel(self, x):
b, c, h, w = x.shape
x = x.reshape(b, 2, -1, h, w)
return x
def forward(self, x):
...
out = self.channel(out, 2)#传了2个参数,报错!
return
正确演示:
class ABC:
...
def channel(self, x, group):
b, c, h, w = x.shape
x = x.reshape(b, group, -1, h, w)
return x
def forward(self, x):
...
out = self.channel(out, 2)#传了2个参数,x=out,group=2
return
或者
class ABC:
...
def channel(self, x, group=2):
b, c, h, w = x.shape
x = x.reshape(b, group, -1, h, w)
return x
def forward(self, x):
...
out = self.channel(out)#传了1个参数,x=out
return