我喜欢使用python类方法来格式化用户输入字符串(例如,“明天-{NEXT_DAY}”),其中类方法可以动态地计算内容。我尝试了以下方法,其中将用要替换的字符串标记python类中的方法(例如MyDateClass()。next_day())。
def format_string(keyword):
def decor(func):
func.keyword = keyword
return func
return decor
class MetaClass(type):
def __new__(mcs, name, bases, class_dict):
cls = super(MetaClass, mcs).__new__(mcs, name, bases, class_dict)
for item in dir(cls):
attr = getattr(cls, item)
if hasattr(attr, 'keyword'):
cls.string_formatter_methods[getattr(attr, 'keyword')] = getattr(cls, item)
return cls
class MyFormatter(string.Formatter):
def get_value(self, key, args, kwargs):
instance = args[0]
if key in instance.string_formatter_methods:
return instance.string_formatter_methods[key](instance)
class MyDateClass(object):
__metaclass__ = MetaClass
string_formatter_methods = {}
def __init__(self):
self.my_date = datetime.now()
@format_string('YEAR')
def year(self):
return self.my_date.year
@format_string('NEXT_DAY')
def next_day(self):
return self.my_date + timedelta(days=1)
def __format__(self, format_spec):
f = MyFormatter()
return f.format(format_spec, self)
print(format(MyDateClass(), "{NEXT_DAY}",))
是否有更好的方法来实现这一目标,或者任何python库已经支持此目标?