python type()和isinstance()无法识别类的实例

时间:2019-05-20 13:38:25

标签: python isinstance

isinstance(object, classinfo)无法识别类的实例。

我打印了type(object)和类本身,以确认它们是相同的类型。他们俩都打印出完全相同的东西,但是当我尝试type(object) == class时,它返回了False

这是该类的代码:

class Convolute(object):
    def __init__(self, channels, filter_shape, pool_shape, pool_type, stride_length=1):
        self.channels = channels
        self.filter_shape = filter_shape
        self.filters = [np.random.randn(filter_shape[0], filter_shape[1]) for i in range(channels)]
        self.biases = [random.random() for i in range (channels)]
        self.stride_length = stride_length
        self.pool_shape = pool_shape
        self.pool_type = pool_type

这是该类的实例:

con1 = n.Convolute(3, (4, 4), (4, 4), 0)

当我尝试验证它们是否为相同类型时,这是python shell中的输出:

>>> import network as n
>>> con1 = n.Convolute(3, (4, 4), (4, 4), 0)
>>> type(con1)
<class 'network.Convolute'>
>>> n.Convolute
<class 'network.Convolute'>
>>> type(con1) == n.Convolute
False
>>> isinstance(con1, n.Convolute)
False

由于type(con1)n.Convolute的输出似乎是相同的,所以我期望isinstance()type(con1) == n.Convolute将返回True,但它们返回的是“ False”。老实说,我很困惑,请帮忙。

-编辑-

type(con1).__name__ == n.Convolute.__name__返回True,但我仍然不知道为什么其他方法无效

问题也存在于我从中导入的文件中,我不仅在导入文件时还遇到了文件本身中的相同问题。这是程序内部的代码:

class Network(object):

    #params for class are layers described by class e.g. ConvolutionalNetwork([Input([...]), Convolute([...]), Flatten(), Dense([...]), (Dense[...]]) 
    #__init__ and setflattensize functions initilize network structures
    def __init__(self, layers):
        self.layers = layers
        self.channels = [layers[0].channels]
        self.shapes = [layers[0].shape]
        for layer, index in zip(layers, range(len(layers))):
            if isinstance(layer, Flatten):
                self.setflattensize(layer, index)
            if isinstance(layer, Dense):
                layer.weights = np.random.randn(self.layers[index-1].size, layer.size) 
            #get list of channels and shapes/sizes that correspond with each layer
            if index>0:
                if self.channels[-1]*layer.channels == 0:
                    self.channels.append(1)
                else:
                    self.channels.append(self.channels[-1]*layer.channels)
                if isinstance(layer, Convolute):
                    self.shapes.append(((self.shapes[-1][0]-layer.filter_shape[0]+1)/layer.pool_shape[0], (self.shapes[-1][1]-layer.filter_shape[1]+1)/layer.pool_shape[1]))
                else:
                    self.shapes.append(layer.size)

if isinstance(layer, Convolute):返回False而不是True。这个问题在前面有更深入的解释。

演示该问题的可运行代码:https://github.com/Ecart33/MachineLearning/blob/master/neural_net/network_debug.py

0 个答案:

没有答案