我花了一些时间学习 Python 的属性魔法。但是当我写一个有小错误的简单案例时,我得到了一个奇怪的结果。这是我的代码:
class PropertyShow(object):
def __init__(self):
self.__num = 90
def setNum(self,value):
self.__num = value
def getNum(self):
return self.__num
def delNum(self):
del self.__num
#num = property(getNum,setNum,delNum)
# I made a mistake here!
__num = property(getNum,setNum,delNum)
class PropertyTwo(object):
def __init__(self):
self.__num = None
@property
def num(self):
"""OK, use a decorator, you can do something here!"""
return self.__num
@num.setter
def num(self,value):
self.__num = value
@num.deleter
def num(self):
del self.__num
one = PropertyShow()
print one.num
two = PropertyTwo()
print two.num
在关键行中,“num = property(getNum,setNum,delNum)”。我把这一行改成了这样粗心,现在像这样“__num = property(getNum,setNum,delNum)”。
这段代码的结果:
File "property.py", line 6, in setNum
self.__num = value
RuntimeError: maximum recursion depth exceeded
- 为什么我在替换
num
to时会得到这个意外的结果__num
? - 如何理解私有变量的魔力
property()
以及为什么要使用私有变量?*