Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不确定如何在python中使用子类和超类完成此任务_Python_Inheritance_Subclass_Superclass - Fatal编程技术网

不确定如何在python中使用子类和超类完成此任务

不确定如何在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

任务是定义一个名为“Shape”的类及其子类“Square”。Square类有一个“init”函数,它以给定的长度作为参数。这两个类都有一个面积函数,可以打印形状的面积,其中形状的面积默认为0

这就是我目前的情况:

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
不是一个函数。你可以先把它修好。