Python __str__ (self) and __unicode__ (self)

Source: Internet
Author: User

Official Document: 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 Repres Entation of an object. This differs from __repr__ () in the It does not has to is a valid Python expression:a more convenient or Conci SE representation may used instead. The return value must is a string object.

The "translation" is called by the inline Method Str () and the "unofficial" string representation of the object is computed through the print statement. This differs from __repr__ () in that it does not need to be a valid Python expression: it can be expressed in a more convenient or concise way. The return type must be a string object.

object. __unicode__ ( self )

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

"Translated" implements Unicode () inline functions, and Unicode objects should be returned. When this method is not defined, instead of a string conversion, the result of conversion is converted to Unicode using the system default encoding.

============ The following content is translated from here ==============

__str__ () is a Python "magic" method that defines the value that should be returned when Object calls Str (). Django uses str (obj) in many places (or related methods, Unicode (obj)-see below), such as displaying its value at the time the Django administration site loads an object, or inserting it as the object's display value into the template. Therefore, we should always return a friendly, user-readable string as an object of __str__. Although this is not necessary, it is advisable to do so. For example:

class Person (models. Model):    = models. Charfield (max_length=50)    = models. Charfield (max_length=50)    def__str__(self):        #  Note Use of DJANGO.UTILS.ENCODING.SMART_STR () here because        #  first_name and last_name would be Unicode strings.        return smart_str ('%s%s' % (Self.first_name, self.last_name)
__unicode__

The __unicode__ () method is called when Unicode () is called on an object. Because the Django database backend returns a Unicode string to the model property, we usually write a __unicode__ () method for our model. The previous example can also be more easily written as:

class Person (models. Model):       = models. Charfield (max_length=50)       = models. Charfield (max_length=50)         def__unicode__(self):           return u ' %s%s ' % (Self.first_name, self.last_name)

If the __unicode__ () method is defined but the __str__ () method is not defined, Django automatically provides a __str__ () method to call the __unicode__ () method, and then converts the result to a UTF-8-encoded string object. In practical development, it is recommended that you only define the __unicode__ () method and let Django handle the conversion of the string object if necessary.

============ Translation End ==========================

In flask, the definition of a data model for a article class can be written in the following notation:

classarticle (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 () @propertydefPost_type (self):returnSelf.__class__.__name__    def __unicode__(self):returnSelf . Title Meta= {        'allow_inheritance': False}

Python __str__ (self) and __unicode__ (self)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.