OiO.lk Blog python Shared class inheritance
python

Shared class inheritance


While I am aware this is weird, I still want to know if it can work mainly for improving understanding.
Basically, it is inheriting a class, but also from the parent class being able to call methods in the sub class.

An example of the issue is as follows:


class Match:
    player = Player(...)
    # other things here

class Player:
    def __init__(self, name, etc)
        ....
        self.display = Display(self)

class Display(Player):
    def __init__(self, player):
        super().__init__(player.name,...)

The goal of this is to call self.player.display.method() from Match to help separate out the display functionality of Player with all the other methods.

Currently the way it is done above leads to recursion between Player and Display.
This is simply fixed by removing the Display class and flattening the methods into Player. But I don’t want to do that. The other option would be to find a way to stop the super().__init__ in Display before it gets to self.display potentially with a flag variable, but I didn’t get this to work.

In my solution I would like:

  1. Display to be able to access all of the instance data and methods in Player so self.name would work in Display for example, without having to call self.player.name or manually assigning self.name
  2. Player to call methods in Display
    Effectively creating a shared class between the two, purely for aesthetic reasons.

I have tried going through super() documentation and articles such as https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

Used guard conditions, such as if not from_super: self.display = ...
Suspect might be able to use hasattr to detect super invoke but didn’t get this to work



You need to sign in to view this answers

Exit mobile version