Magic Methods in Python

Posted by dArignac on Stack Overflow See other posts from Stack Overflow or by dArignac
Published on 2010-06-14T11:40:14Z Indexed on 2010/06/14 11:42 UTC
Read the original article Hit count: 290

Filed under:
|
|

Howdy,

I'm kind of new to Python and I wonder if there is a way to create something like the magic methods in PHP (http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)

My aim is to ease the access of child classes in my model. I basically have a parent class that has n child classes. These classes have three values, a language key, a translation key and a translation value. The are describing a kind of generic translation handling. The parent class can have translations for different translation key each in different languages. E.g. the key "title" can be translated into german and english and the key "description" too (and so far and so on)

I don't want to get the child classes and filter by the set values (at least I want but not explicitly, the concrete implementation behind the magic method would do this). I want to call

parent_class.title['de']
# or also possible maybe
parent_class.title('de')

for getting the translation of title in german (de).

So there has to be a magic method that takes the name of the called method and their params (as in PHP). As far as I dug into Python this is only possible with simple attributes (_getattr_, _setattr_) or with setting/getting directly within the class (_getitem_, _setitem_) which both do not fit my needs.

Maybe there is a solution for this? Please help! Thanks in advance!

© Stack Overflow or respective owner

Related posts about python

Related posts about methods