【问题标题】:Python:@property decorator has Maximum recursion errorPython:@property 装饰器有最大递归错误
【发布时间】:2018-09-30 15:40:35
【问题描述】:

我是 OOPS 和测试属性装饰器的新手。这适用于字符串类型,但对于整数,它在年龄属性时因最大递归错误而失败。有人遇到递归代码吗?我看过一篇在类的语法中添加对象的帖子,但没有太大帮助。

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

【问题讨论】:

标签: python-3.x python-decorators


【解决方案1】:

我发现了一些关于 setter 行为的堆栈溢出的附加信息,这很有效。这也解释了为什么会发生递归。 infinite recursion in python3.3 setter

根据建议,我更新了我的代码。感谢您查看它。

这是更新的sn-p

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

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

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 2011-03-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2016-03-14
    • 2017-01-25
    相关资源
    最近更新 更多