문제

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?

도움이 되었습니까?

해결책

repr should return a string that would re-create the object with eval

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

def __repr__(self):
   return '%s %s'%(self.amount,self.currency)

다른 팁

How to get it from the database is generally uninteresting. Return the way to recreate the object from scratch, e.g. SomeModel(field1, field2, ...).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top