2010-07-28 54 views
0

我想创建一个类,必须是其他类的超类,跟踪他们的属性请求。我想用“的getAttribute”,这得到所有属性的请求,但它产生的递归:Mixin类跟踪属性请求 - __attribute__递归

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

我知道为什么我得到递归:它是自我。 字典调用哪个回调getattribute递归。我试图改变"return object.__getattribute__(self,attr)"的最后一行,就像其他帖子中的建议一样,但是递归被调用。

+2

使用'返回对象.__的getAttribute __(自我,ATTR)'对我的作品。你可以举一个更完整的例子,当你使用这段代码进行递归时。 – 2010-07-28 11:41:49

回答

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] 
+0

嗯......“我试着改变'return object .__ getattribute __(self,attr)'中的最后一行''就像其他帖子中提示的那样,但递归被回想起来。” - OP – delnan 2010-07-28 11:38:47

+0

我已经试过 – 2010-07-28 11:40:38

+0

@delnan,Bob_Bib,我发布的代码是正确的。如果您仍然看到递归,请发布您使用的所有代码和回溯 – 2010-07-28 11:44:20

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:最大递归深度超过”

+0

这应该适合我的答案Mixin类。检查'Es123.py'是否有正确的类。如果它仍然不起作用,请发布整个回溯 – 2010-07-28 13:19:04

+0

是的,它的工作原理!对不起,我留下了错误的版本,所以它不起作用。谢谢。您能否向我解释为什么它可以与object .__ getattribute __(...)协同工作,但是不能仅与__getattribute __(...)协作? – 2010-07-28 13:36:31

+0

'self .__ getattribute__'调用Mixin的'__getattribute__'方法,该方法递归地调用它自己。 'object .__ getattribute__'调用'object'的'__getattribute__'方法,这与'Mixin'的同名方法不同。因此,没有递归。 – unutbu 2010-07-28 14:58:47