python type()和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

下面是类的实例:

^{pr2}$

以下是我尝试验证它们是否为同一类型时在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()和{}将返回{},但它们返回“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


已被浏览了7513次
更新日期: 2020-10-22 22:21:23
0 个回答

目前没有回答

最新Python问答

推荐Python问答