这是一个相当简单的问题,希望你们都可以启发我。在下面的示例中,如何将__repr__定义为动态设置为self.name?
全部谢谢!
import re
inputlist = 'Project="Sparcy" Desc=""\nProject="Libs" Desc=""\nProject="Darwin" Desc=""\nProject="Aaple" Desc="The big project"'
regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')
results = []
for project in inputlist.split("\n"):
items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)]
if len(items) < 2:
print("Houston we have a problem - Only %s k/v pair found for %s" % (len(items), project))
continue
item_dict = dict(items[1:])
item_dict['name'] = items[0][1]
klass = type(items[0][0], (object,), item_dict)
results.append(klass)
print results
我正在寻找的是这个
伪造的代码
for result in results
type(result) → Project
print result → Sparky
答案 0 :(得分:3)
我猜你想要
print results
返回
["Sparcy", "Libs", "Darwin", "Aaple"]
repr(elt)
由type(elt).__repr__
确定。__repr__
表示类的类型。import re
inputlist = '''\
Project="Sparcy" Desc=""
Project="Libs" Desc=""
Project="Darwin" Desc=""
Project="Aaple" Desc="The big project"
Site="Phoenix" Protocol="Cheese"'''
regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')
results = []
for project in inputlist.split("\n"):
items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)]
if len(items) < 2:
print("Houston we have a problem - Only %s k/v pair found for %s" % (len(items), project))
continue
item_dict = dict(items[1:])
item_dict['name'] = items[0][1]
projectname=items[0][0]
metametaklass=type('meta_'+projectname,(type,),{'__repr__':lambda cls: cls.__name__})
metaklass=metametaklass(projectname,(type,),{'__repr__':lambda cls: cls.name})
klass=metaklass(projectname+'_class', (object,), item_dict)
results.append(klass)
print(results)
产量
["Sparcy", "Libs", "Darwin", "Aaple", "Phoenix"]
和
for result in results:
print(type(result))
print(result)
print('-'*80)
产量
Project
"Sparcy"
--------------------------------------------------------------------------------
Project
"Libs"
--------------------------------------------------------------------------------
Project
"Darwin"
--------------------------------------------------------------------------------
Project
"Aaple"
--------------------------------------------------------------------------------
Site
"Phoenix"
--------------------------------------------------------------------------------
PS。请注意,这是__repr__
的变换,因为对象的repr
应该是对象的明确字符串表示。也就是说,它应该提供足够的信息来重现对象。您可能应该定义一个不同的print
函数,而不是弄乱元类。