Python 中的魔术方法
我对 Python 有点陌生,我想知道是否有一种方法可以创建类似 PHP 中的神奇方法的东西(http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)
我的目标是简化模型中子类的访问。我基本上有一个父类,它有 n 个子类。这些类具有三个值:语言键、翻译键和翻译值。它们描述了一种通用翻译处理。父类可以有不同语言的不同翻译键的翻译。例如,键“标题”可以翻译成德语和英语,键“描述”也可以(到目前为止等等)
我不想获取子类并按设置值进行过滤(至少我想要,但是没有明确说明,魔术方法背后的具体实现会做到这一点)。我想请求
parent_class.title['de']
# or also possible maybe
parent_class.title('de')
将标题翻译成德语 (de)。
因此必须有一个神奇的方法来获取被调用方法的名称及其参数(如 PHP 中)。据我深入研究Python,这只能通过简单的属性(__getattr__,__setattr__)或直接在类中设置/获取(__getitem__,__setitem__)来实现,这两者都不符合我的需求。
也许有一个解决方案?请帮忙! 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回parent_class.title 的对象,该对象具有
__getitem__
方法。Return an object for parent_class.title which has a
__getitem__
method.您可以将代码重构为
parent_class['de'].title
。那么这样的事情可能会起作用You could could refactor your code to
parent_class['de'].title
. Then something like this would probaly work