简体   繁体   中英

Reason for calling super class constructor from subclass?

According to Introduction to programming using Python by Liang

class(superclass):

Gives you access to super class

super().__init__()

Instantiates the superclass so you can access its data fields and methods.

This seems incorrect though; In the following code I access the super class using the first keyword class(superclass) but never initiate it using super().__init__() but I still have full access to all methods anyways.

If merely extending the parent class gives me access to its methods, what is the point of calling the parent classes constructor?

Reference: Introduction to programming using Python

CODE:

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

I hope that code didn't come from any introduction to Python book: it's horribly un-Pythonic.

But the answer to your question is that extending gives you access to the methods , but doesn't do any of the setup done in the superclass __init__ . In your example, an instance of square will have access to the getColor method, but actually calling it will give an error because you never ran GeometricObject.__init__ to set the value of self.__color in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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