首页 > 学院 > 开发设计 > 正文

Python__str__(self)和__unicode__(self)

2019-11-14 17:21:33
字体:
来源:转载
供稿:网友

官方文档:https://docs.python.org/2.7/reference/datamodel.html?highlight=__mro__

object.__str__(self)

Called by the str() built-in function and by the PRint statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

【译文】通过内嵌方法str()调用,并通过print语句计算对象的“非正式”字符串表示。这跟__repr__()的区别在于,它不需要是一个合法的Python表达式:可以用一种更便捷或简明的表现方式。返回类型必须是一个string对象。

object.__unicode__(self)

Called to implement unicode() built-in; should return a Unicode object. When this method is not defined, string conversion is attempted, and the result of string conversion is converted to Unicode using the system default encoding.

【译文】实现unicode()内嵌函数;应该返回Unicode对象。当没有定义这个方法时,取而代之的是string转换,转换的结果是用系统默认编码转化为Unicode。

 

============以下内容翻译这里==============

__str__()是Python的一个“魔幻”方法,这个方法定义了当object调用str()时应该返回的值。Django在许多地方使用str(obj)(或者相关方法,unicode(obj)——见下文),比如说在Django管理站点加载一个对象时显示它的值或者作为对象的显示值插入模板中。因此,我们应该总是返回一个友好的,用户可读的字符串作为对象的__str__。尽管这不是必须的,但还是建议这么做。例如:

class Person(models.Model):    first_name = models.CharField(max_length=50)    last_name = models.CharField(max_length=50)    def __str__(self):        # Note use of django.utils.encoding.smart_str() here because        # first_name and last_name will be unicode strings.        return smart_str('%s %s' % (self.first_name, self.last_name)
__unicode__

__unicode__()方法是在一个对象上调用unicode()时被调用的。因为Django的数据库后端会返回Unicode字符串给model属性,所以我们通常会给自己的model写一个__unicode__()方法。前面的例子也可以更简单地写成:

class Person(models.Model):       first_name = models.CharField(max_length=50)       last_name = models.CharField(max_length=50)         def __unicode__(self):           return u'%s %s' % (self.first_name, self.last_name)

如果定义了__unicode__()方法但是没有定义__str__()方法,Django会自动提供一个__str__()方法调用__unicode__()方法,然后把结果转换为UTF-8编码的字符串对象。在实际开发中,建议:只定义__unicode__()方法,需要的话让Django来处理字符串对象的转换。

============翻译结束==========================

在Flask里,定义一个Article类的数据模型相应的写法可以写成:

class Article(db.Document):    Title = db.StringField(max_length=255, required=True)    SegTitle = db.StringField(max_length=255)    Url = db.StringField(max_length=255, required=True)    Id = db.StringField(max_length=255, required=True)    Summary = db.StringField(max_length=255)    Content = db.StringField()    SegContent = db.StringField()    Tags = db.ListField(db.EmbeddedDocumentField(Tag))    StrTags = db.ListField(db.StringField(max_length=30))    LabeledTags = db.ListField(db.StringField(max_length=30))    CrawledDate = db.DateTimeField()    PostDate = db.StringField()    Source = db.StringField()    OriginalSource = db.StringField()    @property    def post_type(self):        return self.__class__.__name__    def __unicode__(self):        return self.Title    meta = {        'allow_inheritance': False    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表