I'm wondering if instance methods can be created automatically in Python when __init__
is executed. Consider this code example where a class is defined to handle some audio file format metadata (exceptions handling and not relevant stuff omitted):
__tags__ = ['album', 'artist', 'date', 'genre', 'title', 'tracknumber']
class Tags():
def __init__(self):
for tag in __tags__:
setattr(self, tag, None)
def print(self):
for k, v in self.__dict__.items():
if v:
print('{}: {}'.format(k, str(v)))
def get(self, *pa):
ret = [getattr(k) for k in pa if k in __tags__]
return ret if len(pa)>1 else ret[0]
def set(self, **ka):
for k, v in ka.items():
if k in __tags__:
setattr(self, k, str(v))
Now:
mytags = Tags()
mytags.set(album='The best of Ennio Morricone', artist='Various Artists')
mytags.print()
print()
mytags.set(genre='Soundtrack', tracknumber=3)
mytags.set(title='Secret Of The Sahara')
mytags.print()
print(mytags.album is mytags.get('album'))
prints:
album: The best of Ennio Morricone
artist: Various Artists
album: The best of Ennio Morricone
artist: Various Artists
genre: Soundtrack
title: Secret Of The Sahara
tracknumber: 3
True
Suppose now I want to add get_<tag>/set_<tag>
methods for every single tag, i.e. mytags.set_album(album)
or title=mytags.get_title()
. Given that mytags.set_album(album)
translates to mytags.set({'album':album,})
, is there a pythonic way to automatically create these methods when the instance is created?
Stupid non-working example just to try to explain what I mean:
class Tags():
def __init__(self):
for tag in __tags__:
setattr(self, tag, None)
setattr(self, 'set_'+tag<reference to passed in argument>,
<reference to the respective self.set() method>)
This would save a lot of typing and, above all, it wouldn't require any change should __tags__
be updated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…