【问题标题】:super().__init__ overwrites an attributesuper().__init__ 覆盖一个属性
【发布时间】:2018-01-26 23:33:30
【问题描述】:

我正在子类初始化程序中设置一个属性,该属性似乎被super().__init__ 的调用覆盖。

from keras.layers import GRU, wrappers


class Dummy(wrappers.Wrapper):
    def __init__(self, layer, **kwargs):
        self.stateful = True
        print(self.stateful)
        super().__init__(layer, **kwargs)
        print(self.stateful)

In [3]: dummy = Dummy(GRU(64, stateful=True))
True
False
In [4]: dummy.stateful
Out[4]: False

我会假设 wrappers.Wrapper 中的某些内容会覆盖该属性,但是内置的包装子类 Bidirectional 具有几乎相同的超类 init 调用(我在实现中基本上遵循了该子类的模式)

class Bidirectional(Wrapper):

    def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):
        ...
        self.stateful = layer.stateful
        ...
        super(Bidirectional, self).__init__(layer, **kwargs)

没有表现出这种行为

In [6]: bidir = wrappers.Bidirectional(GRU(64, stateful=True))

In [7]: bidir.stateful
Out[7]: True

我无法解决这个问题。我在 Python 3.6 下使用 Keras 2.1.3。

附言

我已经尝试在我的子类中将super().__init__(layer, **kwargs) 替换为super(Dummy, self).__init__(layer, **kwargs),但无济于事。

【问题讨论】:

    标签: python python-3.x inheritance keras super


    【解决方案1】:

    您正在查看错误版本的 Bidirectional 源代码。您正在查看的版本似乎是三天前的this one。我相信那个版本和你的代码有同样的错误。

    我认为latest release 中的代码在它自己的__init__开始 处调用super().__init__

    def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):
        super(Bidirectional, self).__init__(layer, **kwargs)
        ...
    

    这样,它的动作发生在祖先构造函数的动作之后,并且它的self.stateful 赋值覆盖了它的祖先。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2011-06-16
    • 1970-01-01
    • 2012-08-26
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多