我正在尝试编写一个简单的控制台颜色实用程序,该实用程序需要一个充满ANSI代码的类,并在我的控制台实用程序上生成一些辅助方法,因此我可以执行console.add(‘text’,’blue’)而不是console.blue( ‘文本’).
我知道我可以静态地定义所有这些(例如def blue(self,s):),但是如果我想添加100个左右的帮助器(不是我愿意,但是如果… )
这是简单的ANSI映射:
class _AnsiColors:
def __init__(self):
self.green = 35
self.red = 1
self.blue = 32
self.yellow = 214
self.amber = 208
self.olive = 106
self.orange = 166
self.purple = 18
self.pink = 197
self.gray = 243
self.dark_gray = 238
self.light_gray = 248
self.black = 0
self.white = 255
self.debug = 24
ansi = _AnsiColors()
和控制台实用程序(代理方法pyfancy和使用颜色):
import copy
from colors import color
from pyfancy import *
from ansi import ansi
class console(object):
def __init__(self, s):
self._s = pyfancy(s)
def add(self, s, c='white'):
if hasattr(ansi, self.add.__name__):
c = self.add.__name__
self._s.add(color(s, fg=getattr(ansi, c)))
return self
def bold(self, s):
self._s.bold(s)
return self
def raw(self, s):
self._s.raw(s)
return self
def dim(self, s):
self._s.dim(s)
return self
def print(self):
self._s.output()
# Inject ansi color convenience methods
for c in vars(ansi):
setattr(console, c, copy.deepcopy(console.add))
getattr(console, c).__name__ = c
然后我可以像这样使用它:
console('raw').bold(' bold').raw(' raw').blue(' blue').red(' red').print()
你可以看到辅助方法蓝色和红色至少执行,所以我的add()复制工作,但这里发生了什么(即使我认为我可以用copy.deepcopy解决它),是当我尝试设置每个方法副本的__name__属性,它将引用设置为添加,我最终得到的颜色相同(ansi.debug).
有没有办法在没有静态定义每个助手的情况下做我想做的事情?
MCVE没有颜色/ pyfancy:
import copy
from ansi import ansi
class console(object):
def __init__(self, s):
self._s = s
def add(self, s, c='white'):
if hasattr(ansi, self.add.__name__):
c = self.add.__name__
self._s += '%s(%s)' % (s, c)
return self
def print(self):
print(self._s)
# Inject ansi color convenience methods
for c in vars(ansi):
setattr(console, c, copy.deepcopy(console.add))
getattr(console, c).__name__ = c
console('white').blue(' blue').red(' red').print()
# white blue(debug) red(debug)