|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class C:
- def _init_ (self, x, y):
- self.x = x
- self.y = y
- def add(self):
- return self.x + self.y
复制代码 学习类的过程中,编译后,输入c=C(2,3)怎么就错误了
- c=C(2,3)
- Traceback (most recent call last):
- File "<pyshell#0>", line 1, in <module>
- c=C(2,3)
- TypeError: C() takes no arguments
复制代码
问题出在类的构造方法上。在Python中,构造方法应该使用双下划线来定义,即 __init__ 而不是 _init_ 。修改代码如下:
- class C:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def add(self):
- return self.x + self.y
- c = C(2, 3)
复制代码
这样就可以正确地创建 C 类的实例了。
|
|