我正在尝试创建一个必须是其他类的超类的类,跟踪它们的属性请求.我想过使用获取所有属性请求的" getattribute ",但它会生成递归:
class Mixin(object):
def __getattribute__ (self, attr):
print self, "getting", attr
return self.__dict__[attr]
Run Code Online (Sandbox Code Playgroud)
我知道为什么我会得到递归:这是为了自我.dict调用以递归方式调用getattribute.我试图"return object.__getattribute__(self,attr)"像其他帖子中建议的那样更改最后一行,但会回忆起递归.
试试这个:
class Mixin(object):
def __getattribute__ (self, attr):
print self, "getting", attr
return object.__getattribute__(self, attr)
Run Code Online (Sandbox Code Playgroud)
如果您仍然遇到递归问题,那么这是由您未向我们展示的代码引起的
>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)
这是与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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
678 次 |
| 最近记录: |