Python:@property装饰器有最大递归错误

时间:2018-04-20 02:12:30

标签: python-3.x python-decorators

我是OOPS新手并测试属性装饰器。这对于字符串类型工作正常,但对于一个整数,当age.Did属性遇到递归代码时,它失败并出现Maximum recursion error。我看过一篇帖子在课堂的语法中添加了一个对象,但它并没有多大帮助。

class person(object):
    def __init__(self, first, last, age=0):
        self.first = first
        self.last = last
        self.age = age


    @property
    def e_mail(self):
        self.email = self.first+'.'+self.last+'@example.com'
        return self.email

    @e_mail.setter
    def e_mail(self,first,last):
        self.first=first
        self.last=last


    @property
    def age(self):
        return self.age

    @age.setter
    def age(self,age):
        self.age = age * 10


x=person('john', 'abc', 5)
print(x.first)
print(x.last)
print(x.e_mail)
print(x.__dict__)
x.first='jj'
x.age=10
print(x.__dict__)

Error message:
Traceback (most recent call last):
  File "C:/Python/022618/test.py", line 30, in <module>
    x=person('john', 'abc', 5)
  File "C:/Python/022618/test.py", line 7, in __init__
    self.age = age
  File "C:/Python/022618/test.py", line 27, in age
    self.age = age * 10
  File "C:/Python/022618/test.py", line 27, in age
    self.age = age * 10
  File "C:/Python/022618/test.py", line 27, in age
    self.age = age * 10
  [Previous line repeated 493 more times]
RecursionError: maximum recursion depth exceeded

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

我已经找到了关于setter行为的堆栈溢出的一些额外信息,这是有效的。这也解释了为什么递归正在发生。 infinite recursion in python3.3 setter

根据建议,我更新了我的代码。谢谢你看一下。

这是更新后的代码段

  @property
    def age(self):
        return self._age

    @age.setter
    def age(self,val):
        self._age = val * 10