我知道如何让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或朋友中的原始内容包装成 ?它甚至可能吗?我假设答案是否定的,或者我会找到答案。但是......有没有语言支持这种事情?这似乎非常有用。 (如果这是一个愚蠢的问题,请不要哄我,而是请解释为什么这种事情似乎甚至不在雷达屏幕上。)
答案 0 :(得分:3)
是的,不知道你能做到多么有活力,但这里看看:
奇怪的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
下面相同的动态世代,但没有关于番茄或Tomate的任何内容。与上面的想法相同,但是您通过循环遍历字典并分配到翻译支持模块来推动翻译。
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
输出:
顺便说一句,上面的german.py的内容只是:腐 布劳
pass
请注意,翻译例程由字典驱动,因此理论上它是非常动态的。
我会将所有属性保存在一个字典中,而不是每个类字典。然后,当您浏览farbe / color,height /höhe,width / breite翻译对时,您需要检查已翻译的类(Tomato)是否具有该属性(宽度),然后将其转换为breite,将其分配给Tomate类。
关于动态属性,这是Sublime Text作为属性骨架生成的内容的调整。如果您使用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))