旧版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 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 16:18 编辑
如上 >>> 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]