不确定如何在python中使用子类和超类完成此任务
任务是定义一个名为“Shape”的类及其子类“Square”。Square类有一个“init”函数,它以给定的长度作为参数。这两个类都有一个面积函数,可以打印形状的面积,其中形状的面积默认为0 这就是我目前的情况:不确定如何在python中使用子类和超类完成此任务,python,inheritance,subclass,superclass,Python,Inheritance,Subclass,Superclass,任务是定义一个名为“Shape”的类及其子类“Square”。Square类有一个“init”函数,它以给定的长度作为参数。这两个类都有一个面积函数,可以打印形状的面积,其中形状的面积默认为0 这就是我目前的情况: class Shape: area = 0 def __init__(self, ??): class Square(Shape): def __init__(self, length): self.length = length
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超类中要做什么。我猜您希望覆盖
Shape
类中的默认函数区域
。然后,当您有一个形状列表时—一些是形状
,一些是正方形
,甚至可能是一些多边形
,您只需调用区域
,就可以打印所有形状,而不知道它是哪个类。多态性
class Shape:
def __init__(self):
pass
def area(self):
print(0)
在创建子类的实例时,调用超类的构造函数也很重要。对于超类的内部结构,可能有一些必要的起始:
class Square:
def __init__(self, length):
self.length = length
super(Square, self).__init__()
在我看来,Shape应该是一个抽象类。如果是这种情况,它可以定义抽象区域方法,然后在子类中为其提供实现。我认为最好在超类中使用
print\u area(self)
方法,它只打印字段区域,并在子类的\uuuu init\uuuu
方法中对其进行初始化,而没有覆盖函数来打印子类中的区域。“两个类都有一个区域函数”area=0
不是一个函数。你可以先把它修好。