我想要有任何類的簡單表示,如{ property = value }
,有沒有汽車__repr__
?自動__repr__方法
10
A
回答
3
你的意思
__dict__
?
8
是的,你可以做一個類「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'}>"
注意,上面的代碼將無法在(直接或間接)引用他們自己的數據結構很好的作用。作爲替代方案,您可以定義在任何類型的工作的功能:
>>> 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'
注意上面的功能沒有遞歸定義的,有目的的,對於前面提到的原因。
1
好吧,我打其他答案一點點,有一個非常漂亮的解決方案:
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)
您可以使用它作爲一個裝飾:
@data
class PythonBean:
def __init__(self):
self.int = 1
self.list = [5, 6, 7]
self.str = "hello"
self.obj = SomeOtherClass()
,並得到一個智能__repr__
出來的方框:
PythonBean(int = 1, obj: <SomeOtherClass>, list = [5, 6, 7], str = 'hello')
這適用於任何遞歸類,包括樹結構。如果您嘗試在類self.ref = self
中添加自引用,該函數將嘗試(成功)解決該問題約一秒。
當然,總是想起你的老闆 - 我的不喜歡這樣的語法糖))
5
最簡單的方法:
def __repr__(self):
return str(self.__dict__)
0
我用這個輔助函數生成再版是爲了我的班。在單元測試功能中運行很容易,即。
def test_makeRepr(self):
makeRepr(Foo, Foo(), "anOptional space delimitedString ToProvideCustom Fields")
這應該輸出一些潛在再版的控制檯,然後你可以複製/粘貼到您的類。
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
相關問題
- 1. 我自己的滾動__repr__
- 2. Python:爲什麼動態添加的__repr__方法不會覆蓋默認值
- 3. 在python中動態創建類和__repr__
- 4. __repr__ for(large)composite objects
- 5. OnReceive()方法自動觸發
- 6. 測試自動化方法
- 7. Windows自動激活方法
- 8. 自動運行方法
- 9. 自動化magmi的方法
- 10. 持久對象和__repr__
- 11. 自動佈線java類和自動佈線方法的區別。
- 12. 自動設置MergeOptions的方法
- 13. 自動代表團在Scala的方法
- 14. 調用方法時自動.toString()?
- 15. 來自javascript的調用動作方法
- 16. 自動生成JButtons的方法?
- 17. 點擊事件自動執行方法
- 18. 如何自動按頭排序方法?
- 19. django如何自動生成方法?
- 20. 排除從自動完成的方法
- 21. 自動調用未知類的方法
- 22. OAuth自動化的解決方法
- 23. 自動輸入shell密碼的方法?
- 24. 連續自動刷新一種方法
- 25. 通知啓動自定義方法/類
- 26. 主動管理和自定義方法
- 27. 自動調用基本方法
- 28. 自動調用實現的方法?
- 29. Get&Set方法的自動生成?
- 30. JQuery自動完成搜索方法
__dict__ is not showing class AnyOtherClass(object):foo ='hello' – 2009-04-16 00:09:19