[英]Use a generic function to do stuff based on the caller?
I have this code which makes it easy to color a string in terminal but it is looking really repetitive. 我有这段代码,可以轻松在终端中给字符串着色,但是看起来确实很重复。 Is there a functional way of doing this more effectively? 有没有更有效的功能方法?
It seems really trival, something like strings blue
, red
etc should point to a generic function, and when you invoke it, you should get the output depending on the caller's name! 看起来确实很简单,像字符串blue
, red
等应该指向一个泛型函数,并且在调用它时,应该根据调用者的名字获得输出!
But apparently such a thing doesn't exist unless I call it as arguements. 但是,除非我称其为论点,否则显然不存在这样的事情。 But then I lose the flexibility of writing blue(bold(italics("Foo")))
which is really the best way to do this from an end user perspetive. 但是后来我失去了编写blue(bold(italics("Foo")))
的灵活性,这对于最终用户来说确实是做到这一点的最佳方法。
Can I have a single function object in the memory and do this more effectively? 我可以在内存中有一个功能对象,并且更有效地做到这一点吗?
bcolors = {"BLUE": '\033[94m',
"HIGH": '\033[93m',
"OKAY": '\033[92m',
"FAIL": '\033[91m',
"BOLD": '\033[1m',
"LINE": '\033[4m',
"ENDC": '\033[0m'
}
def blue(string):
return bcolors["BLUE"] + string + bcolors["ENDC"]
def yellow(string):
return bcolors["HIGH"] + string + bcolors["ENDC"]
def green(string):
return bcolors["OKAY"] + string + bcolors["ENDC"]
def red(string):
return bcolors["FAIL"] + string + bcolors["ENDC"]
def bold(string):
return bcolors["BOLD"] + string + bcolors["ENDC"]
def line(string):
return bcolors["LINE"] + string + bcolors["ENDC"]
A function should never vary its behaviour depending on who called it; 函数绝不能根据调用它的人来改变其行为。 only its arguments should influence its behaviour, anything else is madness. 只有它的论据可以影响它的行为,其他任何事情都是疯狂的。
The obvious refactoring to make it dryer here would be something along these lines: 显然,要使其干燥,可以通过以下方式进行重构:
def _format(start, string):
return bicolors[start] + string + bcolors['ENDC']
def blue(string):
return _format('BLUE', string)
If you wrap this in a class with some magic properties or method call overrides, you could even start deriving the 'BLUE'
parameter from the function call. 如果将其包装在具有一些魔术属性或方法调用替代的类中,则甚至可以从函数调用中派生'BLUE'
参数。
How about build them on the fly?: 如何动态构建它们?:
bcolors = {"BLUE": '\033[94m',
"HIGH": '\033[93m',
"OKAY": '\033[92m',
"FAIL": '\033[91m',
"BOLD": '\033[1m',
"LINE": '\033[4m',
"ENDC": '\033[0m'
}
def _genF(color):
return lambda s: bcolors[color] + s + bcolors["ENDC"]
globals().update({k.lower():_genF(k) for k,v in bcolors.items()})
In[10]: blue("Foo")
Out[10]: '\x1b[94mFoo\x1b[0m'
In[11]: blue(bold(okay("Foo")))
Out[11]: '\x1b[94m\x1b[1m\x1b[92mFoo\x1b[0m\x1b[0m\x1b[0m'
This way yo can just use the bcolors dict info for boulding all the methods you need just modifiying the dict. 这样,您可以仅使用bcolors dict信息来构建您仅需要修改dict的所有方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.