Twistios_Player
Twistios_Player

Reputation: 434

Call the method of the super class in an other method of the subclass

I already asked about something related to the game I am developing. The Problem occured while the developement, but actually it has nothing to do with the game it self.

I have a method ('resize' in a subclass) in my Code which calls the equivalent method in it's super class ('resize' of the superclass).

Here is a code Example:

Subclass:

def do_rotozoom(self):
    # do rotozoom stuff of subclass
def resize(self,factor):
    super().resize(factor)
    self.do_rotozoom()

Superclass:

def do_rotozoom(self):
    #do rotozoom stuff of superclass
def resize(self,factor):
    self.factor = factor
    self.do_rotozoom()

I found a workaround which involved calling super().do_rotozoom() in the Subclass method do_rotozoom() which then was called by the super().resize(). I also found out, that I could in this case remove the line self.do_rotozoom().

In this case it was a pretty easy fix, but what would I do in a more complex scenario, for example, if I need to call the method do_rotozoom() with other variables in the superclass than I do in the subclass/another specific implementation? In other words, how am I able to select which method I want to use in a specific context?

Normaly you are only able to reach the super-methods from the subclass, but no super-methods (not of it's superclass but it's own methods) from the superclass.

I have not found a better title... :D

Upvotes: 0

Views: 97

Answers (2)

tripleee
tripleee

Reputation: 189317

The very definition of a subclass is that it inherits everything from the superclass except the methods and attributes it overrides.

A subclass can refer to its superclass and its method implementations with super(), like you already do in your example.

Either don't override do_rotozoom, or refer to the superclass method with super().do_rotozoom() where that's the behavior you require.

Upvotes: 0

tawfikboujeh
tawfikboujeh

Reputation: 107

Developers tend to prefer Composition over inheritance , it's much more manageable .

what i advise you to do is to include an instance of your superclass in you subclass and use it whenever you want to .

Upvotes: 1

Related Questions