Python classes losing attributes

后端 未结 3 1706
甜味超标
甜味超标 2021-01-02 06:37

I have a peculiar python problem. During the course of execution of my gtk python application, some of my class objects mysteriously lose attributes, causing some of the fun

3条回答
  •  梦毁少年i
    2021-01-02 07:00

    PyQT (and therefore maybe also PyGtk or other framework) has the weird behaviour that actually raising an AttributeError somewhere within/below the attribute code will actually make python report that the called attribute on that object does not exist.

    There is a (somewhat more official) story somewhere about why this is (and is actually right and understandable behaviour). It has something to do with __getattr__ being defined on a base class: The meganism by which that works is that if calling the attribute on an object results in an AttributeError, the __getattr__ method is called. But that method has no idea what 'attribute' was actually not found. And since the (PyQt.QObject) __getattr__ was designed to implement 'specific' attributes, it decides to raise another AttributeError mentioning the 'called' attribute.

    Anyway, what could be is that you are inheriting from an object which uses __getattr__ somewhere and that your own attribute code does call (another) attribute which does, indeed, not exist. What you can do to check this is:

    @property
    def myproperty:
       try:
          doStuff..
       except AttributeError as e:
          print "Got ya! It is withing the attribute:", repr(e)
          raise ValueError("Got an AttributeError within my attribute!")
    

    Update/Note: Also, if you are implementing __getattr__ yourself on your DeckerGenericList object, be carefull with it for this very same reason! Raising AttributeError's within __getattr__ will most of the time lead to seemingly weird behaviour like this. Note that there is no easy fix: The 'real' AttributeError only carries a string message (and not specificly the actual attribute name), but much more important: the __getattr__ function never sees the original AttributeError in the first place.

提交回复
热议问题