Python __str__(self)和__unicode__(self)
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=)
last_name = models.CharField(max_length=) 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=)
last_name = models.CharField(max_length=) 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=, required=True)
SegTitle = db.StringField(max_length=)
Url = db.StringField(max_length=, required=True)
Id = db.StringField(max_length=, required=True)
Summary = db.StringField(max_length=)
Content = db.StringField()
SegContent = db.StringField()
Tags = db.ListField(db.EmbeddedDocumentField(Tag))
StrTags = db.ListField(db.StringField(max_length=))
LabeledTags = db.ListField(db.StringField(max_length=))
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
}
Python __str__(self)和__unicode__(self)的更多相关文章
- python __str__ & __repr__ & __cmp__
For ( __str__ ),we going to see a example ... and find who is working for ... #!/usr/bin/python clas ...
- python __str__() 和 __repr__()是干啥的
1. 没定义__str__() print的时候得不到自己想要的东西 类默认转化的字符串基本没有我们想要的一些东西,仅仅包含了类的名称以及实例的 ID (理解为 Python 对象的内存地址即可).虽 ...
- Python __str__函数
class Cat: def __init__(self,_name): self.name = _name def __str__(self): return "i am %s" ...
- python __str__ , __repr__区别
Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数. 函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式 (如果没有等价的语法,则会 ...
- python - __str__ 和 __repr__
内建函数str()和repr() (representation,表达,表示)或反引号操作符(``)可以方便地以字符串的方式获取对象的内容.类型.数值属性等信息.str()函数得到的字符串可读性好(故 ...
- Python __str__(self)
python 在打印一个实例化对象时,打印的是对象的地址,比如:<__main__.Workers object at 0x00000000255A9AC8> 而__str__(self) ...
- python __str__ 和__repr__方法
看下面的例子就明白了 class Test(object): def __init__(self, value='hello, world!'): self.data = value >> ...
- 关于django模型里面的__str__和__unicode__
python3 django模型里面 使用 __str__ 如果使用__unicode__是无效的 简而言之,就是__str__和__unicode__都是为了再管理站点中加载这个表时想显示什 ...
- Python自动化之__unicode__
def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) 如果定义了__unicode__()方法但是没有定 ...
随机推荐
- pat(A)1041. Be Unique(哈希)
1.链接:点击打开链接 2.代码: #include<cstdio> #include<iostream> #include<cstring> using name ...
- 2016/04/18 session cookie 对比 应用 <?php session_start() / setcookie()?>
①会话 huihua.php <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...
- linux epoll的实现原理
1 linux的poll操作 linux文件的poll操作有两个主要目的:第一,主动查看该文件上是否有读写事件:第二,提供操作waitqueue的接口给epoll等上层接口使用,比如epoll可以通过 ...
- Test redis
单机测试: public class RedisClient{ private Jedis jedis; private JedisPool jedisPool; private ShardedJed ...
- mongodb02
memcached redis : kv数据库(key/value) mongodb 文档数据库,存储的是文档(Bson->json对象二进制化后叫bson,js的二进制对象,引擎是用js实现的 ...
- mybatis批量操作数据
批量查询语句: List<MoiraiProductResource> selectBatchInfo(List<Long> idList); <!-- 批量查询 --& ...
- 线程之间的通信socketpair【学习笔记】【原创】
平台信息:内核:linux3.1.0系统:android5.0平台:tiny4412 作者:庄泽彬(欢迎转载,请注明作者) 说明: 韦老师的安卓视频学习笔记 一.在一个进程中多个线程如何进行通信,主要 ...
- bzoj 5017 炸弹
题目大意: 直线上有n个炸弹有坐标x和半径r 当一个炸弹被引爆时 若有炸弹的坐标在该炸弹坐标+-r范围内则另一个炸弹也被引爆 求先引爆每一个炸弹最终会引爆多少炸弹 思路: 可以想到n平方连边然后tar ...
- BZOJ2283: [Sdoi2011]火星移民
Description 在2xyz年,人类已经移民到了火星上.由于工业的需要,人们开始在火星上采矿.火星的矿区是一个边长为N的正六边形,为了方便规划,整个矿区被分为6*N*N个正三角形的区域(如图1) ...
- Java Socket实战之三:传输对象
转自:https://i.cnblogs.com/EditPosts.aspx?opt=1 前面两篇文章介绍了怎样建立Java Socket通信,这一篇说一下怎样使用Java Socket来传输对象. ...