【问题标题】:Python - "object layout"Python - “对象布局”
【发布时间】:2010-07-22 12:27:44
【问题描述】:

有人可以描述以下异常吗?什么是“对象布局”以及它是如何定义的?谢谢

Traceback (most recent call last):
  File "test_gui.py", line 5, in <module>
    suite = AlgorithmEngine('gui_suite')
  File "/home/honza/Research/Voiar/algorithm.py", line 169, in __init__
    self.algorithms = self._initAlgorithms()
  File "/home/honza/Research/Voiar/algorithm.py", line 232, in _initAlgorithms
    self._initGUIAlgorithm(obj)
  File "/home/honza/Research/Voiar/algorithm.py", line 218, in _initGUIAlgorithm
    cls.__bases__ = bases
TypeError: __bases__ assignment: 'QWidget' object layout differs from 'GUIAlgorithm'

【问题讨论】:

    标签: python class-design


    【解决方案1】:

    这意味着您尝试更改对象的类型(通过分配给__bases__)并且新类型与旧类型不兼容。当两种类型的底层 C 数据结构不同时,就会发生这种情况。

    请参阅http://www.mail-archive.com/python-list@python.org/msg52950.html 了解可能触发此异常的类型之间的差异列表。

    【讨论】:

    • 在进入 Python 的(暴露的)内部结构时,通常会遇到多少警告,这有点令人失望——Python 的一致性和简洁性就在那里被打破了。这只是一个例子。
    • @ErikKaplun 即时替换__bases__ 是骇人听闻的,因此无法对语言的整体印象做出贡献:)
    • 将从一开始的纯 Python 类添加到在层次结构中添加 collections.abc.Mapping 以帮助使我原来的 __class__ 表现得更像一个字典。分配给self.__class__(同样是一个纯 Python 类)然后给出这个确切的错误。去掉子类化collections.abc.Mapping,错误就消失了。
    【解决方案2】:

    在我的情况下,当我尝试使用更改也具有__slots__ 的对象的__class__ 时发生错误,如下所示:

    class Base:
        __slots__ = ('a', 'b', 'c')
    
    class Child(Base):
        pass
    
    
    obj = Base()
    obj.__class__ = Child  
    # -> TypeError: __class__ assignment: 'Child' object layout differs from 'Base'
    

    【讨论】:

    • 孩子应该有__slots__ = tuple()
    猜你喜欢
    • 2012-08-20
    • 2019-01-06
    • 1970-01-01
    • 2011-01-09
    • 2011-01-16
    • 2014-03-07
    • 2013-08-07
    • 2010-12-10
    • 1970-01-01
    相关资源
    最近更新 更多