Search code examples
pythonclassinheritancemixinscomposition

Obtain attributes from a non-parent mixin class


I have a class "TrackPage" which is a web page class that has information obtained from the page, e.g. track title, URL, and file - the file downloaded from the page.

The track attribute is itself a class "Track" which should take some attributes values from the TrackPage (like title, but not URL) from which it was called, but also have its own attributes like length, size etc:

class TrackPage(BasePage):
    def __init__(self):
        self.track_title = 'foo'
        self.url = 'www.bar.com'
        self.file = 'baz.mp3'
        self.track = Track() 


class Track:
    def __init__(self):
        self.track_title =    # Take TrackPage attribute
        self.file =           # Take TrackPage attribute
        self.length =         # Obtained through processing TrackPage attribute file
        self.size =           # Obtained through processing TrackPage attribute file

 

From what I read, it seems like using mixin class which contains the attributes of TrackPage I want would be the way to go, but I can't find examples similar to what I'm trying to do.

What's the best way of structuring my classes for a scenario like this?


Solution

  • You have at least two options.

    First is to pass the TrackPage instance in and collect the attributes you want:

    class TrackPage(BasePage):
        def __init__(self):
            self.track_title = 'foo'
            self.url = 'www.bar.com'
            self.file = 'baz.mp3'
            self.track = Track(self) 
    
    class Track:
        def __init__(self, tp):
            self.track_title = tp.track_title 
            self.file = tp.file
            self.length = tp.file.length # or however
            self.size = tp.file.size # or however
    

    The second is to just keep the TrackPage instance and reference the attribute when they are needed:

    class TrackPage(BasePage):
        def __init__(self):
            self.track_title = 'foo'
            self.url = 'www.bar.com'
            self.file = 'baz.mp3'
            self.track = Track(self) 
    
    class Track:
        def __init__(self, tp):
            self.track_page = tp
    
        def get_file(self):
            return self.track_page.file