Python - 使用__getattribute__方法 [英] Python - Using __getattribute__ method

查看:625
本文介绍了Python - 使用__getattribute__方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖对类中一个变量的访问,但是正常返回所有其他变量。我如何通过 __ getattribute __

来实现这一点。我尝试了下面的内容但是我得到一个递归错误:

  class D(object):
def __init __
self.test = 20
self.test2 = 21
def __getattribute __(self,name):
如果name =='test':
return 0.
else:
return self .__ dict __ [name]

>>>> print D()。test
0.0
>>> print D()。test2
...
RuntimeError:超出最大递归深度cmp


解决方案

由于调用同一个函数,你的 __ getattribute __ 会得到递归错误。如果你使用 object __ getattribute __ ,它的工作原理:

  class D(object):
def __init __(self):
self.test = 20
self.test2 = 21
def __getattribute __(self,name):
如果name =='test':
return 0.
else:
return object .__ getattribute __(self,name)

这是因为 object 类。通过调用 __ getattribute __ 的基本版本,您可以避免之前的递归地狱。



Ipython输出, foo.py:

 在[1]:from foo import * 

在[2] d = D()

In [3]:d.test
Out [3]:0.0

在[4]:d.test2
Out [4]:21

更新: b
$ b

更多属性访问新样式类 ,他们建议这样做,以避免无限递归。


I want to override access to one variable in a class, but return all others normally. How do I accomplish this with __getattribute__?

I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return self.__dict__[name]

>>> print D().test
0.0
>>> print D().test2
...
RuntimeError: maximum recursion depth exceeded in cmp

解决方案

You get a recursion error because you call the same function, your __getattribute__. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

这篇关于Python - 使用__getattribute__方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆