Home > other >  Does python have super().__init__().area() this kind of method?
Does python have super().__init__().area() this kind of method?

Time:09-28

class Square():
    def __init__(self,side):
        self.side = side
    
    def area(self):
        return self.side * self.side

class cube(Square):
    def area(self):
        return super().__init__().area() * 6
        
    def volume(self):
        return super().area() * self.side()
        
        
c = Square(4)
# print(c.area())
# print(c.volume())

d = cube(4)
print(d.area())

Can we actually use super().__init__().area() a method like this in python ? If so then what does it mean ? The above code throws an error.

TypeError: __init__() missing 1 required positional argument: 'side'

Then can you please tell me what type of arguments we should use inside __init__ and super() ?

CodePudding user response:

super().__init__().area() * 6

Does not makes, as __init__ must return None or as __init__ docs say

(...)no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

and None has not .area method.

CodePudding user response:

Can we actually use super().__init__().area() a method like this in python ? If so then what does it mean ?

It means nothing because it's complete nonsense: super() lets you access methods and attributes in a superclass context, so super().__init__() will call the superclass' __init__ (outside of __init__ which is a terrible idea), and that returns nothing, hence the failure.

Then can you please tell me what type of arguments we should use inside __init__ and super() ?

The question itself is wrong because all its assumptions are incorrect. If you want to call the superclass' area you just:

def area(self):
    return super().area()

though the inheritance relationship here makes no sense, there is no "IS A" relationship between a square and a cube, they're not substitutable for one another.

  • Related