Reputation: 10033
I am trying to implement a project using class inheritance
, where parent class is:
class radio:
def __init__(self, artist=None, track=None, genre=None):
self.artist = artist
self.track = track
self.genre = genre
then I create methods
for each attribute
(non working examples):
def seed_artist(self):
results = api.search(q=self.artist, type='artist')
return results
def seed_track(self):
results = api.search(q=self.track, type='track')
return results
def seed_genre(self):
results = api.search(q=self.genre, type='genre')
return results
the user is going to pick a seed above (only one), being it either artist
, track
, genre
or mood
, and that's why I initialize all arguments with None
, leaving the argument value to be inserted at inheritance level.
the inherited class
is:
class playlist(radio):
def __init__(self,user):
radio.__init__(self, artist, track, genre)
lets say user inputs at command line a track seed
, and my script ends up starting with a global variable:
track = 'karma police'
this way, all other attributes (artist
, genre
) remain None
.
when I create an instance, say:
jeff = playlist('Jeff Smith')
It will throw an error saying that genre
and artist
are not defined, and I would have to inherit only track
attribute, like so:
radio.__init__(self, track)
I know I could start the script with global variables defined:
track = None
genre = None
artist = None
and this would allow me to have:
radio.__init__(self, artist, track, genre)
but this seems to me rather redundant...
Is there a workaround this, with no need for initial values of global variables set to None
, keeping all the code within class scope definitions?
Upvotes: 1
Views: 145
Reputation: 599450
You don't have those variables to pass, so don't try and pass them. The parent class already has defaults for them, so just pass the one you need:
radio.__init__(self, artist=artist)
Upvotes: 0
Reputation: 251345
Instead of using a separate global variable for each field, use a single dictionary for all fields. Then you can pass the dictionary as keyword arguments.
That is, instead of creating a global variable called artist
, create a dictionary called radio_fields
or something. When the user inputs their query, set a key on this dict:
radio_fields = {}
...
# when you get the user's command
radio_fields['track'] = 'Karma Police'
Now you can call radio.__init__(self, **radio_fields)
. This will pass as arguments whatever keys are in radio_fields
. If there is only one, only that one will be passed, and the others will take their default values as you defined them when you defined radio.__init__
.
There might be a better way to structure your overall program, but it's hard to say based on what you've shown here. For instance, it's unclear why playlist
only accepts one user
argument. If playlist
accepted all the field arguments that radio
accepted, it could pass them on to radio
without any problem.
Upvotes: 1