This article mainly introduces an infinite recursion problem caused by the descriptor and property of python, for more information about the problem, see the following. I have a python code similar to this:
The code is as follows:
# Coding: UTF-8
Class A (object ):
@ Property
Def _ value (self ):
# Raise AttributeError ("test ")
Return {"v": "This is a test ."}
Def _ getattr _ (self, key ):
Print "_ getattr __:", key
Return self. _ value [key]
If _ name _ = '_ main __':
A = ()
Print a. v
You can get the correct result after running
The code is as follows:
_ Getattr __: v
This is a test.
However, note that
The code is as follows:
# Raise AttributeError ("test ")
If the comment in this line is removed, the AttributeError exception is thrown in the _ value method, which makes things somewhat strange. When the program runs, it does not throw an exception, but enters an infinite recursion:
The code is as follows:
File "attr_test.py", line 12, in _ getattr __
Return self. _ value [key]
File "attr_test.py", line 12, in _ getattr __
Return self. _ value [key]
RuntimeError: maximum recursion depth exceeded while calling a Python object
After searching through multiple parties, the problem is found to be a property modifier. property is actually a descriptor. This text can be found in python doc:
The code is as follows:
Object. _ get _ (self, instance, owner)
Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access ). owner is always the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner. this method shocould return the (computed) attribute value or raise an AttributeError exception.
In this way, when the user accesses. _ value, AttributeError is thrown, and the _ getattr _ method is called to try to obtain it. In this way, the program becomes infinite recursion.
This problem does not seem complicated, but when your _ value method throws AttributeError in a relatively obscure manner, debugging will be more difficult.