I am having an issue passing an instance variable of an object to an instance method.
I have searched for this elsewhere, but all I keep finding is information on how the object is passed to the method using self
, which I already know, or just tutorials on general differences between class and instance methods that don't specifically answer my question. The answer to my question definitely exists somewhere, I think I just don't know what to actually ask for.
In my code, I have this class:
class SongData:
def __init__(self, datapoint):
self.artist = datapoint['artist']
self.track = datapoint['name']
def xtradata_rm(self, regex, string=None):
if string is None:
string = self
srchrslts = re.search(regex, string)
if srchrslts is not None:
if regex == 'f.*?t':
self = self.replace(string,'')
self.xtradata_rm('\((.*?)\)')
else:
self.xtradata_rm('f.*?t', srchrslts)
def example_method(self):
#This one isn't actually in the code, included for ease of explanation.
print(self)
#some more methods irrelevant to question down here.
Imagine we instantiate an object by doing song = SongData(datapoint)
. The method xtradata_rm
is supposed to search either the song.artist
or song.track
string for a section in brackets, then if the section found contains any form of the word "featuring" remove that from the string and then try again until no more bracketed expressions with brackets containing "featuring" are found.
I am aware now this is probably 100% the wrong usage of self, but I don't know what to put in its place to achieve the behaviour I want. So then in my script I try to do:
file_list = glob.glob("*procData.json")
for datafname in file_list:
datafile = json.load(open(datafname))
for i, datapoint in enumerate(datafile['EnvDict']):
song = SongData(datapoint)
song.track.xtradata_rm('\((.*?)\)')
song.releasefetch(lfmapi)
song.dcsearcher(dcapi)
datapoint.update({"album": song.release, "year": song.year})
with open("upd" + datafname, 'w') as output:
json.dump(datafile, output)
but then I get this error:
Traceback (most recent call last):
song.track.xtradata_rm('\((.*?)\)')
AttributeError: 'str' object has no attribute 'xtradata_rm'
If I comment out that line, the code runs.
So my first question is, in general, what do I have to do so I can go song.track.example_method()
or song.artist.example_method()
and get track_name
or artist_name
printed in the console as expected respectively.
My second question is, how can I do the same with xtradata_rm
(i.e.
be able to do song.track.xtradata_rm('\((.*?)\)')
and essentially insert song.track
in place of self
within the method), and how does xtradata_rm
being recursive and trying to pass the instance variable implicitly to itself within itself change things?