Receive our weekly advanced programming tips for FREE
01.May
How to use __getatrr__
0
| 0 votes
Autor: bookkeeper
Chapter: Python

Python is very dynamic, you can control almost everything, one of this is the method __getatrr__ which will be only called if the request attribute was not found.

You can use the __getattr__ for example to print the attribute name in request language. 

class Country(object):
    LANGUAGES = {'de':"Deutschland",
                 'es':'Alemania',
                 'fr':'Allemagne'
                }
    name = "Germany"
   
    """Only called if request attribute wasn't found """
    def __getattr__(self, name):
        if '_' in name: #
            lang = name.split('_')[-1::][0] # get the language
            if lang in self.LANGUAGES: # do we have a translation?
                return self.LANGUAGES.get(lang)# translation
        return self.name

def main():
    country = Country()
    print country.name # default
    print country.name_de
    print country.name_es
    print country.name_fr
    print country.name_cn #no translation


if __name__ == '__main__':
    main()

This is very powerfull, we overwrite the method __getattr__ and fill it with our logic.

To create a translation we have to overwrite the method __setatrr__

class Country(object):
    LANGUAGES = {'de':"Deutschland",
                 'es':'Alemania',
                 'fr':'Allemagne'
                }
    name = "Germany"
    
    """Only called if request attribute wasn't found """
    def __getattr__(self, name):
        if '_' in name:
            lang = name.split('_')[-1::][0]
            if lang in self.LANGUAGES:
                return self.LANGUAGES.get(lang)
        return self.name

    """Set a translation """
    def __setattr__(self, name, value):
        if '_' in name:
            lang = name.split('_')[-1::][0]
            self.LANGUAGES[lang] = value

def main():
    country = Country()
    print country.name_nl
    country.name_nl = "Duitsland"
    print country.name_nl


if __name__ == '__main__':
    main()

We overwrite the method __setattr__ an add the translation to LANGUAGES

Well, I hope it was helpfull :)