Mixin类用于跟踪属性请求 - __attribute__递归

时间:2010-07-28 11:24:31

标签: python recursion

我正在尝试创建一个必须是其他类的超类的类,跟踪它们的属性请求。我想过使用“ getattribute ”获取所有属性请求,但它会生成递归:

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

我知道为什么我会得到递归:这是自我。 dict 调用,它以递归方式回忆 getattribute 。我试图改变"return object.__getattribute__(self,attr)"中的最后一行,就像其他帖子中建议的一样,但是会回忆起递归。

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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返回“RuntimeError:超出最大递归深度”