持久对象和 __repr__
对于持久化的对象,处理 __repr__() 函数的最佳方法是什么?例如,代表数据库(关系或对象)中的一行。
根据Python文档,__repr__()
应该返回一个字符串,该字符串将使用eval()
重新创建对象,这样(大致)eval(repr(obj) )) == obj
,或不精确表示的括号表示法。通常这意味着将对象无法重新生成的所有数据转储到字符串中。然而,对于持久对象,重新创建对象可能就像从数据库检索数据一样简单。
那么,对于这样的对象,是所有对象数据还是只是 __repr__()
字符串中的主键?
What would be the best way to handle the __repr__()
function for an object that is made persistent? For example, one that is representing a row in a database (relational or object).
According to Python docs, __repr__()
should return a string that would re-create the object with eval()
such that (roughly) eval(repr(obj)) == obj
, or bracket notation for inexact representations. Usually this would mean dumping all the data that can't be regenerated by the object into the string. However, for persistent objects recreating the object could be as simple as retrieving the data from the database.
So, for such objects then, all object data or just the primary key in the __repr__()
string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对于 int 或 string 或 float 等简单类型是合法的,但对于具有 15+ 列的多列 DB 对象来说不可用
例如,如果我有一个代表价格的类,那么合理的做法是
__repr__
显示了它的主要特征:金额和货币That is legal for simple types like int or string or float, but not usable for multi-column DB object with say 15+ columns
For example if I had a class representing price, it would be reasonable to make the
__repr__
show the main characteristics of it: amount and currency如何从数据库中获取它通常是无趣的。返回从头开始重新创建对象的方法,例如
SomeModel(field1, field2, ...)
。How to get it from the database is generally uninteresting. Return the way to recreate the object from scratch, e.g.
SomeModel(field1, field2, ...)
.