可以用Python翻译函数、方法等吗?

2024-04-25 07:02:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何让Python本地化函数的输出,至少包括任何涉及字符串的内容。这里有很多关于这个的好问题。我想做一些可能更愚蠢,但也更基本的事情。你知道吗

事实上,这是一个障碍,最(流行?)语言是用英语的一种或另一种。好吧,我们来处理。但是当我创建自己的东西时呢?你知道吗

class Tomato:
    def __init__(self,color):
        self.color = color

很高兴我可以这样做

> T = Tomato('red')
> T.color
'red'

假设我不想本地化颜色名称,而是要本地化单词color本身-或Tomato。所以其他人可以这样做,比如说德语

> T = Tomate('rot')
> T.farbe
'rot'

我不必懂英语,也不必编写只向用户公开字符串的应用程序界面。你知道吗

他妈的,一个人怎么能用gettext或friends把原来的东西包起来呢?有可能吗?我假设答案是否定的,否则我早就找到了。但是。。。有什么语言可以支持这种事情吗?这看起来很有用。(如果这是一个愚蠢的问题,请不要对我指手画脚,相反,请解释为什么这类问题甚至没有出现在雷达屏幕上。)


Tags: 函数字符串self语言内容init颜色def
1条回答
网友
1楼 · 发布于 2024-04-25 07:02:10

是啊,不知道你能做得多么有活力,但下面是一个例子:

奇怪的type()行为的灵感来自

http://www.jeffknupp.com/blog/2013/12/28/improve-your-python-metaclasses-and-dynamic-classes-with-type/

class Tomato(object):
    def __init__(self,color):
        self.color = color
T = Tomato('red')
T.color


di_trad = {"Tomato": "Tomate"}

def xlator(self, attrname):
    di = {"farbe":"color"}
    attr_eng = di.get(attrname,attrname)
    return getattr(self, attr_eng)

这很有效。。。但仅仅因为Tomate是硬编码的。。。你不想这样做,但它显示了你的基本想法。你知道吗

Tomate = type("Tomate",(Tomato,),dict(__getattr__=xlator))
t = Tomate('rot')
print t.farbe

#to me this is the weak point ... emitting arbitrary dynamic classnames
#into the current module.  mind you, we really want to do this against 
#say an import german module...
# and we want to allow drive which classes we translate dynamically as well

下面是相同的动态生成,但这里没有关于番茄或番茄的编码。与上面的想法相同,但是您通过循环dict并将其分配给翻译支持模块来驱动翻译。你知道吗

di_class_trad = {"Tomato" :"Tomate"}

import german
for engname, tradname in di_class_trad.items():
    cls_ = globals().get(engname)
    setattr(german, tradname, type(tradname,(cls_,),dict(__getattr__=xlator)))
    #in any case

t2 = german.Tomate("blau")
print t2.farbe

输出:

rot blau

顺便说一句,内容德语.py以上只是:

pass

请注意,翻译例程是由字典驱动的,因此理论上它是相当动态的。你知道吗

我会把所有的属性放在一个字典里,而不是一个每类字典。然后,当您通过farbe/color、height/höhe、width/breite翻译对时,您需要在将其翻译breite分配给类Tomate之前检查翻译类(Tomato)是否具有该属性(width)。你知道吗

关于动态属性,这是对Sublime文本作为属性骨架生成的内容的调整。如果用xlator字典的循环驱动它,并将属性分配给目标类,谁知道呢,它可能会工作。。。你知道吗

def farbe():
    doc = "The farbe property."
    def fget(self):
        return self.color
    def fset(self, value):
        self.color = value
    def fdel(self):
        del self.color
    return locals()


#farbe = property(**farbe())
#would this work?
setattr(tgt_class,"farbe", property(**farbe()))

可爱,但同样,不确定这将有多少真正的用途,除非你保持实际的用户可见的翻译功能相当基本的操作。在类型调用中为Tomate分配一个第二祖先类来添加一些大脑来保持理智可能会有所帮助。你知道吗

 setattr(german, tradname, type(tradname,(cls_,SanityManagerClass),dict(__getattr__=xlator))

相关问题 更多 >