混入类追踪属性请求 - __attribute__ 递归

0 投票
2 回答
743 浏览
提问于 2025-04-16 01:57

我正在尝试创建一个类,这个类必须是其他类的父类,并且能够跟踪它们对属性的请求。我想到了使用getattribute,这个方法可以获取所有属性请求,但它会导致递归调用的问题:

class Mixin(object):
 def __getattribute__ (self, attr):
  print self, "getting", attr
         return self.__dict__[attr]

我知道为什么会出现递归调用:这是因为self.dict的调用又一次调用了getattribute,导致了递归。我尝试按照其他帖子中的建议,把最后一行改成"return object.__getattribute__(self,attr)",但还是出现了递归调用。

2 个回答

0

这是代码:

from Es123 import Mixin
class Mylist(Mixin):
    def __init__ (self, lista):
        if not type (lista) == type (""):
            self.value = lista[:]
    def __add__ (self,some):
        return self.value + some
    def __getitem__ (self,item):
        return self.value[item]
    def __getslice__ (self, beg, end):
        return self.value[beg:end]
a = Mylist ([1,2])
a.value

然后,Python 返回了一个错误信息:“运行时错误:超过了最大递归深度”。

5

试试这个:

class Mixin(object):
    def __getattribute__ (self, attr):
        print self, "getting", attr
        return object.__getattribute__(self, attr)

如果你还是遇到递归的问题,那是因为你没有给我们看完整的代码

>>> class Mixin(object):
...     def __getattribute__ (self, attr):
...         print self, "getting", attr
...         return object.__getattribute__(self, attr)
...
>>> Mixin().__str__
<__main__.Mixin object at 0x00B47870> getting __str__
<method-wrapper '__str__' of Mixin object at 0x00B47870>
>>> Mixin().foobar
<__main__.Mixin object at 0x00B47670> getting foobar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getattribute__
AttributeError: 'Mixin' object has no attribute 'foobar'
>>>

这是和Bob的Mylist结合后的结果

>>> class Mylist(Mixin):
...     def __init__ (self, lista):
...         if not type (lista) == type (""):
...             self.value = lista[:]
...     def __add__ (self,some):
...         return self.value + some
...     def __getitem__ (self,item):
...         return self.value[item]
...     def __getslice__ (self, beg, end):
...         return self.value[beg:end]
...
>>> a=Mylist([1,2])
>>> a.value
<__main__.Mylist object at 0x00B47A90> getting value
[1, 2]

撰写回答