views:

89

answers:

3

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!

+3  A: 

Return an object for parent_class.title which has a __getitem__ method.

class parent_class:
    def __init__(self):
        self.title = multilang("hello world");

class multilang:
    def __init__(self, text):
        pass
    def __getitem__(self, key):
        if key == 'en':
            return "hello world";
Sjoerd
Well, that's a solution I haven't thought about, but it fits extremly good to my needs as I have to consider some other environment facts I didn't mention ;)Thank your for this!
dArignac
A: 

You could could refactor your code to parent_class['de'].title. Then something like this would probaly work

from collections import defaultdict

class X(object):
    def __init__(self, title = "", description = ""):
        self.title = title
        self.description = description

parent_class = defaultdict(X)

parent_class['en'] = X("title", "description")
parent_class['de'].title = "Titel"
biocs
Good solution, but unfortunatly does not work in my environment because of some limitations I'm bound to. But thank you anyway!
dArignac
A: 

http://docs.python.org/reference/datamodel.html#special-method-names

petraszd
Read this, didn't found a concrete solution though.
dArignac