想要充实自己 发表于 2020-8-18 15:40:12

旧版45讲里面的题目。。。为什么我的方法出错了

目标是实现这个
static/image/hrline/line4.png

>>> demo = Demo()
>>> demo.x
'FishC'
>>> demo.x = "X-man"
>>> demo.x
'X-man'

static/image/hrline/line4.png
我做的是这个:

static/image/hrline/line4.png
class C:

      def __getattr__(self,name):
                return 'FishC'
      def __setattr__(self,name):
                super().__setattr__(self,name)
      

static/image/hrline/line4.png
结果是这样的:
>>> c = C()
>>> c.x
'FishC'
>>> c.x = "X-man"
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
    c.x = "X-man"
TypeError: __setattr__() takes 2 positional arguments but 3 were given
>>>

sunrise085 发表于 2020-8-18 15:59:01

本帖最后由 sunrise085 于 2020-8-18 16:00 编辑

      def __setattr__(self,name):
                super().__setattr__(self,name)
这个函数写错了.
      def __setattr__(self,name, value):
                super().__setattr__(self,name, value)
其中self指代该类型的实例对象(c),name指代你要修改的成员变量名(x),value指代你将要修改的变量值("X-man")

fall_bernana 发表于 2020-8-18 15:59:14

本帖最后由 fall_bernana 于 2020-8-18 16:18 编辑

如上

想要充实自己 发表于 2020-8-19 09:13:53

>>> c = C()
>>> c.x
'FishC'
>>> c.x = 'x-man'
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
    c.x = 'x-man'
File "D:\test.py", line 6, in __setattr__
    super().__setattr__(self,name,value)
TypeError:expected 2 arguments, got 3
错误依旧
页: [1]
查看完整版本: 旧版45讲里面的题目。。。为什么我的方法出错了