【Python】一个最基础,但是超难看出来的类声明为tuple的BUG

直接上代码,我在layer.py中定义了这样一个类:

class QConv2d(nn.Conv2d):
    ''' A standard Conv2d layer that quantizes input and weights before performing mult(weights, input). It quantizes outputs also. '''
    def __init__(self, inCh: int, outCh: int, kDim: int, stride: int = 1, quantization: dict = None):
        super(QConv2d,self).__init__(inCh, outCh, kDim, stride=stride, bias = False, padding = int((kDim-1)/2))

        self.isWinograd = False
        self.quantize = True if quantization['q'] else False

        if self.quantize:
            self.bits = quantization['bits']
            self.Quantize_weights = Quant(self.bits)
            self.Quantize_input = Quant(self.bits)
            self.Quantize_output = Quant(self.bits)
        else:
            self.bits = 'FP'

    def forward(self, input):
        if self.quantize:
            qinput = self.Quantize_input(input)
            qweight = self.Quantize_weights(self.weight)
            return self.Quantize_output(nn.functional.conv2d(qinput, qweight, self.bias, self.stride, self.padding, self.dilation, self.groups))
        else:
            return nn.functional.conv2d(input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)

然后我在model.py中对其进行声明:

self.conv1 = QConv2d(in_planes, planes, kDim=3, stride=stride, quantization=Q_args),

结果,出现了这样的报错:

TypeError: 'tuple' object is not callable

打印self.conv1可以看到:

<class 'tuple'>
(QConv2d(
  16, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False
  (Quantize_weights): Quant()
  (Quantize_input): Quant()
  (Quantize_output): Quant()
),)

为啥这个class是个tuple类型呀!?

原因非常简单,我在声明类的时候, 末尾多了一个逗号!!!!!! 修改后如下:

self.conv1 = QConv2d(in_planes, planes, kDim=3, stride=stride, quantization=Q_args)

再打印self.conv1看看:

<class 'src.layers.Conv2d'>
QConv2d(                                                                                                                                                                                                                                                             
  32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False
  (Quantize_weights): Quant()
  (Quantize_input): Quant()
  (Quantize_output): Quant()
)

小结一句,Python末尾是没有分号或者逗号的,要防止误敲无关字符!

你可能感兴趣的:(机器学习,Python,【深度学习/神经网络】Deep,Learning,python,bug,开发语言)