|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Rectangle:
- def __init__(self, width = 0, height = 0):
- self.width = width
- self.height = height
- def __setattr__(self, name, value):
- if name == 'square':
- self.width = value
- self.height = value
- else:
- super( ).__setattr__(name, value)
- def getArea(self):
- return self.width*self.height
复制代码
Windows系统下,Python2版本,运行后老是出现如下错误,求帮助解答。(小白一只)
- r = Rectangle(2,3)
- Traceback (most recent call last):
- File "<pyshell#26>", line 1, in <module>
- r = Rectangle(2,3)
- File "E:\python programm\try.py", line 3, in __init__
- self.width = width
- File "E:\python programm\try.py", line 11, in __setattr__
- super( ).__setattr__(name, value)
- TypeError: super() takes at least 1 argument (0 given)
复制代码
不知道原因,明明是跟着小甲鱼一起敲的代码!!!
但是换成下列方法就是正确的
- class Rectangle:
- def __init__(self, width = 0, height = 0):
- self.width = width
- self.height = height
- def __setattr__(self, name, value):
- if name == 'square':
- self.width = value
- self.height = value
- else:
- self.__dict__[name] = value
- def getArea(self):
- return self.width*self.height
复制代码
然后可以得到正确结果。
- >>> r = Rectangle(2,3)
- >>> r.square = 10
- >>> r.width
- 10
- >>> r.getArea()
- 100
- >>>
复制代码
- class Rectangle(object):
- def __init__(self, width = 0, height = 0):
- self.width = width
- self.height = height
- def __setattr__(self, name, value):
- if name == 'square':
- self.width = value
- self.height = value
- else:
- super( ).__setattr__(name, value)
- def getArea(self):
- return self.width*self.height
复制代码
|
|