V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yannick
V2EX  ›  Python

__getattr__死循环的问题

  •  
  •   yannick · Aug 8, 2018 · 2205 views
    This topic created in 2823 days ago, the information mentioned may be changed or developed.
    class Proxy:
    def __init__(self, obj):
    # self._obj = obj,则调用__getattr__就会死循环,而改成 self._obj = obj,则不会;
    self.obj = obj

    def __getattr__(self, item):
    return getattr(self.obj, item)


    class Spam:
    def __init__(self, x):
    self.x = x

    def bar(self, y):
    print('Spam.bar:', self.x, y)


    if __name__ == "__main__":
    spam = Spam(10.05)
    proxy = Proxy(spam)
    print(proxy.x)

    仅仅是将 Proxy 实例属性由_obj 的成 obj,就会造成__getattr__无限循环,这个怎么理解?谢谢。
    3 replies    2018-08-08 14:38:48 +08:00
    ngnetboy
        1
    ngnetboy  
       Aug 8, 2018
    不知道你的环境是什么样的,使用你的代码跑了一下,没发现什么问题。
    zhusimaji
        2
    zhusimaji  
       Aug 8, 2018
    哈哈,楼主肯定是在__init__初始化函数改了,忘记在 getattr 里面修改了,导致在获取的时候无线循环一直到报 error
    <script src="https://gist.github.com/zhusimaji/df879dd537a6729b6201f456e2c08b71.js"></script>
    yannick
        3
    yannick  
    OP
       Aug 8, 2018
    @ngnetboy @zhusimaji 谢谢二位,原因找到了!有一段__setattr__的代码没贴出来,在__setattr__中调用了__getattr__,没做一些拦截处理,造成重复调用__getattr__,话说,这几个魔术方法真是死循环的高危险操作呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2454 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 05:13 · PVG 13:13 · LAX 22:13 · JFK 01:13
    ♥ Do have faith in what you're doing.