不确定如何使用python中的子类和超类完成此任务
问题描述:
任务是定义名为'Shape'的类及其子类'Square'。 Square类有一个'init'函数,它将给定的长度作为参数。这两个类都有一个区域功能,可以打印形状的区域,其中Shape的区域默认为0。不确定如何使用python中的子类和超类完成此任务
这是我的时刻:
class Shape:
area = 0
def __init__(self, ??):
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
a = (self.length * self.length)
print('The area of a square with a side length of %f is %f' % (self.length, a))
s = Square(2)
s.area()
我不确定在外形超要做什么。
答
我想你想覆盖Shape
类中的默认功能area
。然后,当你有一个形状列表 - 一些Shape
,一些Square
,甚至可能是一些Polygon
,你可以打电话area
,而不知道它是哪一类。多态性!
class Shape:
def __init__(self):
pass
def area(self):
print(0)
创建子类的实例时调用超类的构造函数也很重要。对于超类的内部结构可能有一些必要的启动:
class Square:
def __init__(self, length):
self.length = length
super(Square, self).__init__()
在我看来像形状应该是一个抽象类。如果是这样的话,它可以定义抽象区域方法,然后在子类中提供实现。 – MeterLongCat
我认为在超类中有一个'print_area(self)'方法是可取的,它只打印字段区域并在子类的__init__方法中初始化它,并且没有覆盖函数来打印子类中的区域。 – Chris
_“这两个类都有区域功能”_' area = 0'不是函数。你可以先解决这个问题。 –