Python 自动报告法
我想要任何类的简单表示,比如Python 自动报告法,python,Python,我想要任何类的简单表示,比如{property=value},是否有自动\uuuu repr\uuuu __dict__ 是的,您可以创建一个类“AutoRepr”,并让所有其他类扩展它: >>> class AutoRepr(object): ... def __repr__(self): ... items = ("%s = %r" % (k, v) for k, v in self.__dict__.items()) ... re
{property=value}
,是否有自动\uuuu repr\uuuu
__dict__
是的,您可以创建一个类“AutoRepr”,并让所有其他类扩展它:
>>> class AutoRepr(object):
... def __repr__(self):
... items = ("%s = %r" % (k, v) for k, v in self.__dict__.items())
... return "<%s: {%s}>" % (self.__class__.__name__, ', '.join(items))
...
>>> class AnyOtherClass(AutoRepr):
... def __init__(self):
... self.foo = 'foo'
... self.bar = 'bar'
...
>>> repr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
>class AutoRepr(对象):
... 定义报告(自我):
... items=(%s=%r”%(k,v)表示self中的k,v.\u dict\uuuu.items()
... 返回“%”(self.\uuuuuu class.\uuuuuuu.\uuuuuuu name.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
...
>>>类别任何其他类别(自动恢复):
... 定义初始化(自):
... self.foo='foo'
... self.bar='bar'
...
>>>repr(AnyOtherClass())
""
请注意,上面的代码不会很好地作用于(直接或间接)引用自身的数据结构。作为替代方案,您可以定义适用于任何类型的函数:
>>> def autoRepr(obj):
... try:
... items = ("%s = %r" % (k, v) for k, v in obj.__dict__.items())
... return "<%s: {%s}." % (obj.__class__.__name__, ', '.join(items))
... except AttributeError:
... return repr(obj)
...
>>> class AnyOtherClass(object):
... def __init__(self):
... self.foo = 'foo'
... self.bar = 'bar'
...
>>> autoRepr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
>>> autoRepr(7)
'7'
>>> autoRepr(None)
'None'
def自动恢复(obj):
... 尝试:
... items=(%s=%r”%(k,v)表示对象中的k,v.\uu dict\uu.items()
... return“嗯,我对其他答案做了一点尝试,得到了一个非常漂亮的解决方案:
class data:
@staticmethod
def repr(obj):
items = []
for prop, value in obj.__dict__.items():
try:
item = "%s = %r" % (prop, value)
assert len(item) < 20
except:
item = "%s: <%s>" % (prop, value.__class__.__name__)
items.append(item)
return "%s(%s)" % (obj.__class__.__name__, ', '.join(items))
def __init__(self, cls):
cls.__repr__ = data.repr
self.cls = cls
def __call__(self, *args, **kwargs):
return self.cls(*args, **kwargs)
并从盒子中取出一个智能的\uuuu repr\uuuu
:
PythonBean(int = 1, obj: <SomeOtherClass>, list = [5, 6, 7], str = 'hello')
PythonBean(int=1,obj:,list=[5,6,7],str='hello')
这适用于任何递归类,包括树结构。如果您尝试在类self.ref=self
中放置一个自引用,该函数将尝试(成功地)计算大约一秒钟
当然,一定要记住你的老板-我的老板不喜欢这样的语法(最简单的方法:
def __repr__(self):
return str(self.__dict__)
我使用这个helper函数为我的类生成reprs
def test_makeRepr(self):
makeRepr(Foo, Foo(), "anOptional space delimitedString ToProvideCustom Fields")
这将向控制台输出大量潜在的repr,然后您可以将其复制/粘贴到类中
def makeRepr(classObj, instance = None, customFields = None):
"""Code writing helper function that will generate a __repr__ function that can be copy/pasted into a class definition.
Args:
classObj (class):
instance (class):
customFields (string):
Returns:
None:
Always call the __repr__ function afterwards to ensure expected output.
ie. print(foo)
def __repr__(self):
msg = "<Foo(var1 = {}, var2 = {})>"
attributes = [self.var1, self.var2]
return msg.format(*attributes)
"""
if isinstance(instance, classObj):
className = instance.__class__.__name__
else:
className=classObj.__name__
print('Generating a __repr__ function for: ', className,"\n")
print("\tClass Type: "+classObj.__name__, "has the following fields:")
print("\t"+" ".join(classObj.__dict__.keys()),"\n")
if instance:
print("\tInstance of: "+instance.__class__.__name__, "has the following fields:")
print("\t"+" ".join(instance.__dict__.keys()),"\n")
else:
print('\tInstance of: Instance not provided.\n')
if customFields:
print("\t"+"These fields were provided to makeRepr:")
print("\t"+customFields,"\n")
else:
print("\t"+"These fields were provided to makeRepr: None\n")
print("Edit the list of fields, and rerun makeRepr with the new list if necessary.\n\n")
print("repr with class type:\n")
classResult = buildRepr( classObj.__name__, " ".join(classObj.__dict__.keys()))
print(classResult,"\n\n")
if isinstance(instance, classObj):
instanceResult = buildRepr( instance.__class__.__name__, " ".join(instance.__dict__.keys()))
else:
instanceResult = "\t-----Instance not provided."
print("repr with instance of class:\n")
print(instanceResult,"\n\n")
if customFields:
customResult = buildRepr( classObj.__name__, customFields)
else:
customResult = '\t-----Custom fields not provided'
print("repr with custom fields and class name:\n")
print(customResult,"\n\n")
print('Current __repr__')
print("Class Object: ",classObj)
if instance:
print("Instance: ",instance.__repr__())
else:
print("Instance: ", "None")
def buildRepr(typeName,fields):
funcDefLine = "def __repr__(self):"
msgLineBase = ' msg = "<{typename}({attribute})>"'
attributeListLineBase = ' attributes = [{attributeList}]'
returnLine = ' return msg.format(*attributes)'
x = ['self.' + x for x in fields.split()]
xResult = ", ".join(x)
y = [x + ' = {}' for x in fields.split()]
yResult = ', '.join(y)
msgLine = msgLineBase.format(typename = typeName, attribute = yResult)
attributeListLine = attributeListLineBase.format(attributeList = xResult)
result = "{declaration}\n{message}\n{attributes}\n{returnLine}".format(declaration = funcDefLine,
message = msgLine,
attributes = attributeListLine,
returnLine =returnLine )
return result
def makeRepr(classObj,instance=None,customFields=None):
“”“编写代码帮助函数,该函数将生成一个可复制/粘贴到类定义中的_repr__u;函数。”。
Args:
classObj(类):
实例(类):
自定义字段(字符串):
返回:
无:
始终在之后调用_repr________)函数,以确保预期的输出。
即打印(foo)
定义报告(自我):
msg=“”
属性=[self.var1,self.var2]
返回消息格式(*属性)
"""
如果isinstance(实例,classObj):
className=实例。\类。\名称。\名称__
其他:
className=classObj.\uu名称__
print('为:'生成一个_repr__函数,类名,“\n”)
打印(“\t类类型:”+classObj.\uuuuuu名称\uuuuuuu,“具有以下字段:”)
打印(“\t”+”.join(classObj.\u dict.\u.keys()),“\n”)
例如:
打印(“\t状态:”+实例.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu类.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
打印(“\t”+”.join(instance.\u dict\u.keys()),“\n”)
其他:
打印('\t未提供实例的状态。\n')
如果自定义字段:
打印(“\t”+”这些字段提供给makeRepr:”)
打印(“\t”+自定义字段,“\n”)
其他:
打印(“\t”+”这些字段已提供给makeRepr:None\n”)
打印(“编辑字段列表,必要时使用新列表重新运行makeRepr。\n\n”)
打印(“类类型为:\n的报告”)
classResult=buildRepr(classObj.\uuuuu name.\uuuuuu,“.”join(classObj.\uuuuuu dict.\uuuuuuuu.keys())
打印(classResult,“\n\n”)
如果isinstance(实例,classObj):
instanceResult=buildRepr(instance
其他:
instanceResult=“\t-----未提供实例。”
打印(“用类的实例报告:\n”)
打印(instanceResult,“\n\n”)
如果自定义字段:
customResult=buildRepr(classObj.\uuuuu name\uuuuuuu,customFields)
其他:
customResult='\t-----未提供自定义字段'
打印(“带有自定义字段和类名的repr:\n”)
打印(自定义结果,“\n\n”)
打印(“当前报告”)
打印(“类对象:”,classObj)
例如:
打印(“实例:,实例._urepr__;())
其他:
打印(“实例:,“无”)
def buildRepr(类型名称、字段):
funcDefLine=“def\uuu repr\uuu(self):”
msgLineBase='msg=”“'
attributeListLineBase='attributes=[{attributeList}]'
returnLine='return msg.format(*attributes)'
x=['self.+x表示字段中的x.split()]
xResult=“,”。连接(x)
y=[x+'={}'表示字段中的x.split()]
yResult=','。联接(y)
msgLine=msgLineBase.format(typename=typename,attribute=yResult)
attributeListLine=attributeListLineBase.format(attributeList=xResult)
result=“{declaration}\n{message}\n{attributes}\n{returnLine}”。格式(declaration=funcDefLine,
message=msgLine,
属性=属性行,
返回线=返回线)
返回结果
dict没有显示类AnyOtherClass(object):foo='hello'Wow,Stackoverflow社区当时似乎非常宽容。你能给出一个关于你答案的最小代码示例吗?
def makeRepr(classObj, instance = None, customFields = None):
"""Code writing helper function that will generate a __repr__ function that can be copy/pasted into a class definition.
Args:
classObj (class):
instance (class):
customFields (string):
Returns:
None:
Always call the __repr__ function afterwards to ensure expected output.
ie. print(foo)
def __repr__(self):
msg = "<Foo(var1 = {}, var2 = {})>"
attributes = [self.var1, self.var2]
return msg.format(*attributes)
"""
if isinstance(instance, classObj):
className = instance.__class__.__name__
else:
className=classObj.__name__
print('Generating a __repr__ function for: ', className,"\n")
print("\tClass Type: "+classObj.__name__, "has the following fields:")
print("\t"+" ".join(classObj.__dict__.keys()),"\n")
if instance:
print("\tInstance of: "+instance.__class__.__name__, "has the following fields:")
print("\t"+" ".join(instance.__dict__.keys()),"\n")
else:
print('\tInstance of: Instance not provided.\n')
if customFields:
print("\t"+"These fields were provided to makeRepr:")
print("\t"+customFields,"\n")
else:
print("\t"+"These fields were provided to makeRepr: None\n")
print("Edit the list of fields, and rerun makeRepr with the new list if necessary.\n\n")
print("repr with class type:\n")
classResult = buildRepr( classObj.__name__, " ".join(classObj.__dict__.keys()))
print(classResult,"\n\n")
if isinstance(instance, classObj):
instanceResult = buildRepr( instance.__class__.__name__, " ".join(instance.__dict__.keys()))
else:
instanceResult = "\t-----Instance not provided."
print("repr with instance of class:\n")
print(instanceResult,"\n\n")
if customFields:
customResult = buildRepr( classObj.__name__, customFields)
else:
customResult = '\t-----Custom fields not provided'
print("repr with custom fields and class name:\n")
print(customResult,"\n\n")
print('Current __repr__')
print("Class Object: ",classObj)
if instance:
print("Instance: ",instance.__repr__())
else:
print("Instance: ", "None")
def buildRepr(typeName,fields):
funcDefLine = "def __repr__(self):"
msgLineBase = ' msg = "<{typename}({attribute})>"'
attributeListLineBase = ' attributes = [{attributeList}]'
returnLine = ' return msg.format(*attributes)'
x = ['self.' + x for x in fields.split()]
xResult = ", ".join(x)
y = [x + ' = {}' for x in fields.split()]
yResult = ', '.join(y)
msgLine = msgLineBase.format(typename = typeName, attribute = yResult)
attributeListLine = attributeListLineBase.format(attributeList = xResult)
result = "{declaration}\n{message}\n{attributes}\n{returnLine}".format(declaration = funcDefLine,
message = msgLine,
attributes = attributeListLine,
returnLine =returnLine )
return result
class MyClass:
def __init__(self, foo: str, bar: int):
self.foo = foo
self.bar = bar
self._baz: bool = True
def __repr__(self):
f"{self.__class__.__name__}({', '.join([f'{k}={v}' for k, v in self.__dict__.items() if not k.startswith('_')])})"
mc = MyClass('a', 99)
print(mc)
# MyClass(foo=a, bar=99)
# ^^^ Note that _baz=True was hidden here