繁体   English   中英

从子类调用超类构造函数的原因?

[英]Reason for calling super class constructor from subclass?

根据Liang的Python编程介绍

class(superclass):

让您进入超一流

super().__init__()

实例化超类,以便您可以访问其数据字段和方法。

不过,这似乎不正确; 在下面的代码中,我使用第一个关键字class(superclass)访问超类,但从未使用super().__ init __()对其进行初始化,但无论如何我仍然可以完全访问所有方法。

如果仅扩展父类使我可以访问其方法,那么调用父类的构造函数有什么意义?

参考: 使用Python编程简介

码:

class GeometricObject:
    def __init__(self,color = "green",filled = True):
        self.__color = color
        self.__filled = filled

    def getColor(self):
        return self.__color

    def setColor(self, color):
        self.__color = color

    def isFilled(self):
        return self.__filled

    def setFilled(self,filled):
        self.__filled = filled

    def __str__(self):
        return "Color: " + self.__color + \
               " and filled: " + str(self.__filled)

class square(GeometricObject):
    def __init__(self,width,height):
        self.__width = width
        self.__height = height

    def getHeight(self):
        return self.__height
    def getWidth(self):
        return self.__width

    def setHeight(self,height):
        self.__height = height
    def setWidth(self,width):
        self.__width = width

我希望代码不会来自Python书籍的任何介绍:这是非常糟糕的非Python语言。

但是问题的答案是,扩展使您可以访问方法 ,但不执行超类__init__中的任何设置。 在您的示例中, square实例可以访问getColor方法,但是实际上调用它会产生错误,因为您从未运行过GeometricObject.__init__来首先设置self.__color的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM