我有两个类。第一个类是RegularPolygon,第二个是RegularClass的子类继承。我想设置默认值为边数= 4。我尝试过(这是我对这段代码的评论),但结果是">非默认参数跟随默认参数python类…">
class RegularPolygon:
def __init__(self, no_of_sides, side_length):
self.no_of_sides = no_of_sides
self.side_length = side_length
def perimeter(self):
keliling_poligon = self.no_of_sides * self.side_length
return keliling_poligon
def interior_angle(self):
int_angle = (self.no_of_sides - 2) * 180/self.no_of_sides
return int_angle
def exterior_angle(self):
𝑒𝑥𝑡_𝑎𝑛𝑔𝑙𝑒=360/self.no_of_sides
return ext_angle
class Square(RegularPolygon):
def __init__(self, no_of_sides, side_length):
super().__init__(no_of_sides, side_length)
self.no_of_sides = 4
def area(self):
area_square = self.side_length**2
return area_square
def diagonal(self):
diagonal_square = self.side_length*(2**0.5)
return diagonal_square
square_1 = Square(5)
s_perim = square_1.perimeter()
s_area = square_1.area()
angl_int = square_1.interior_angle()
angl_ext = square_1.exterior_angle()
diagonal = square_1.diagonal()
result = (s_perim, s_area, angl_int, angl_ext, diagonal)
print(result)
我想把默认值4在子类Square然后产生error
TypeError Traceback (most recent call last)
<ipython-input-6-cdd5b6433650> in <module>
29 return diagonal_square
30
---> 31 bujursangkar = Square(5)
32
33 keliling = bujursangkar.perimeter()
TypeError: __init__() missing 1 required positional argument: 'side_length'
当您有两个变量定义def __init__(self, no_of_sides, side_length):
时,您应该使用square_1 = Square(4,5)
而不是square_1 = Square(5)
。
您也可以使用以下方式:
class Square(RegularPolygon):
def __init__(self, side_length, no_of_sides = 4):
super().__init__(no_of_sides, side_length)
def area(self):
# ... code ...
在后一种情况下,如果您想在需要时覆盖no_of_sides
的值,则可以。