这是我在这里的第一篇文章,所以如果有任何错误,请告诉我。
这是我的代码:
import math
class Square():
def __init__(self, length):
self.length = length
def getL(self,length):
self.length = length
print(length)
def getP(self,length):
return length * 4
def getA(self,length):
return length * length
def __add__(self,another_square):
return Square(self.length + another_square.length)
s1 = Square()
s2 = Square()
print(s1.setL(5))
print(s1.getP(5))
print(s1.getA(5))
print(s2.getP(12))
print(s2.getA(15))
s3 = s1 + s2
print(s3.getA())
当我运行它时会给我一个TypeError:
Traceback (most recent call last):
File "C:\Users\user\Desktop\programming.py", line 21, in <module>
s1 = Square()
TypeError: __init__() missing 1 required positional argument:'length'
我想知道我的代码有什么问题,任何帮助都会受到赞赏。
答案 0 :(得分:2)
您需要将参数传递给构造函数。
s1 = Square(1) # will call Square.__init__(self, 1)
s2 = Square(2) # will call Square.__init__(self, 2)
这不是一个大问题。
我重写了你的课程:
import math
class Square():
def __init__(self, length): #return an instance of this class with 'length' as the default length.
self.length = length
def setL(self,length): #pass length to the instance and override the original length.
self.length = length
def getL(self): #get the length of instance.
return self.length
def getP(self): #get the perimeter of instance.
return self.length * 4
def getA(self): #get the area of instance.
return self.length ** 2
def __add__(self,another_square): #return a new instance of this class with 'self.length + another_square.length' as the default length.
return Square(self.length + another_square.length)
我认为你在阅读我的代码后可以意识到你真正的问题是什么。并且对上面的代码进行了测试。
s1 = Square(1)
s2 = Square(2)
print(s1.getP())
print(s1.getA())
print(s2.getP())
print(s2.getA())
s3 = s1 + s2
print(s3.getA())
output:
4
1
8
4
9
答案 1 :(得分:1)
你的类init需要一个长度参数,你试图创建s1而不给它一个
答案 2 :(得分:1)
您正在初始化Square
的实例而未指定length
参数。
s1 = Square()
s2 = Square()
然而根据你的定义
def __init__(self, length):
self.length = length
length
是必需的位置参数。您需要为此参数定义合理的默认值,例如
def __init__(self, length=1):
self.length = length
或在初始化对象时明确提供它(例如s1 = Square(1)
)
答案 3 :(得分:1)
您应该使用构造函数来传递值。 像这样。
s1 = Square(100)
s2 = Square(482)
答案 4 :(得分:0)
您必须提供长度,因为在 init ()所需的长度参数:
s1 = Square(5)
s2 = Square(5)