![](/img/trans.png)
[英]Using Unittest/PyTest/etc. to test a Python function that works with files
[英]Is it possible to translate function, methods, etc. in 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或朋友中呢? 可能吗? 我以为答案是否定的,否则我会找到答案的。 但是...是否有任何语言可以支持这种事情? 这似乎很有用。 (如果这是一个愚蠢的问题,请不要怪我,而是请解释一下为什么这种事情在雷达屏幕上似乎都不存在。)
是的,不知道您可以如何做到这一点,但这里是一个外观:
奇怪的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
下面是相同的动态生成,但是这里没有关于Tomato或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翻译对时,您需要在将翻译的breite分配给Tomate类之前,检查翻译的类(Tomato)是否具有该属性(宽度)。
关于动态属性,这是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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.