鱼C论坛

 找回密码
 立即注册
查看: 1175|回复: 1

[已解决]第045讲课程问题请益

[复制链接]
发表于 2018-4-11 11:20:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class R:
  2.         def __init__(self):
  3.                 self.counter = 0
  4.         def __setattr__(self, name, value):
  5.                 self.counter = value
复制代码


>>> r = R()
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    r = R()
  File "<pyshell#37>", line 3, in __init__
    self.counter = 0
  File "<pyshell#37>", line 5, in __setattr__
    self.counter = value
  File "<pyshell#37>", line 5, in __setattr__
    self.counter = value
  File "<pyshell#37>", line 5, in __setattr__
    self.counter = value
  [Previous line repeated 326 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

因self.counter = 0赋值操作触发__setattr__, 而其中self.counter = value又是赋值操作,所以造成死循环。

  1. class R:
  2.         def __init__(self):
  3.                 self.counter = 0
  4.         def __setattr__(self, name, value):
  5.                 self.counter = self.counter + value
复制代码


>>> r = R()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r = R()
  File "<pyshell#34>", line 3, in __init__
    self.counter = 0
  File "<pyshell#34>", line 5, in __setattr__
    self.counter = self.counter + value
AttributeError: 'R' object has no attribute 'counter'

请问为什么程式码只有些改变,为什么却变成没有属性counter呢?真得想不懂? ? ?

最佳答案
2018-4-11 20:33:59
counter属性还没定义出去,先进行了赋值,赋值里对counter属性操作,当然没定义
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-4-11 20:33:59 | 显示全部楼层    本楼为最佳答案   
counter属性还没定义出去,先进行了赋值,赋值里对counter属性操作,当然没定义
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-10 11:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表