How to write general get methods for a class?
<p>recently I started using oop in python. I would like to write a general get or set method for the initiated attributes. For example, there is the class Song with several attributes and a corresponding get method. I would like to avoid the multiple if statements. With just two attributes it does not matter, but if there are >5 attributes the code would be difficult to read. Is it possible to use a string in args to get the value from <strong>init</strong> whithout defining all possible cases?</p>

<pre><code>class Song(object):

    def __init__(self,title,prod):
        self.title = title
        self.prod = prod

    def getParam(self,*args):
        retPar = dict()
        if 'title' in args: 
            print(self.title)
            retPar['title'] = self.title
        if 'prod' in args:
            print(self.prod)
            retPar['prod'] = self.prod
        return(retPar)
</code></pre>

<p>I am not sure, if this is possible, because I could not find anything. How can I do this? </p>

<blockquote>
  <p>provide a function for colleagues who are not familiar with the python syntax, such that they do not have to access the the attritubes directly. For plotting and such things</p>
  
  <p>because python is not necessarily taught and the dot syntax is confusing for people who have basic knowledge in matlab</p>
</blockquote>

<p>I'd argue that this can easily be taught and you shouldn't bend over backwards for something so simpleâ¦ but assuming this is really what you want, this looks like a much better idea:</p>

<pre><code>class Song(object):
    def __init__(self, title, prod):
        self.title = title
        self.prod = prod

    def __getitem__(self, key):
        return getattr(self, key)

song = Song('Foo', 'Bar')
print song['title']
</code></pre>

<p>See <a href="https://docs.python.org/2/reference/datamodel.html#object.__getitem__" rel="nofollow">https://docs.python.org/2/reference/datamodel.html#object.__getitem__</a> and <a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow">https://docs.python.org/2/library/functions.html#getattr</a>.</p>

python oop methods args